设计题目二:编写Applet,包含两个按钮,一个按钮用于放大Applet上的一串字符串,一个按钮用于缩小;连续点击可不断放大或缩小.
本题目是利用程序中setFont(f1),通过改变程序中变量i的值,来实现Applet中字体的放大和缩小。在程序中,用鼠标单击按钮时,AWT事件处理系统将向按钮发送一个ActionEvent事件对象。应用程序作出反应要为按钮注册事件监听程序实现ActionListenner接口,在程序中,通过addActionListener()方法为按钮注册了监听程序,在程序运行时,单击两按钮会自动实现字符串的放大与缩小。
//Enlarge
import java.awt.*;
import java.awt.event.*;
public class Enlarge extends WindowAdapter implements ActionListener{
private Frame f;
private Panel p;
private Button b1,b2;
private TextField t;
int i=100;
public static void main(String args[]){
Enlarge be=new Enlarge();
be.go();}
public void go(){
f=new Frame();
p=new Panel();
t=new TextField("王睿",10);
b1=new Button("放大");
b2=new Button("缩小");
p.add(b1);
p.add(b2);
f.add("Center",t);
f.add("South",p);
f.addWindowListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
f.setSize(300,300);
f.setVisible(true);
}
//实现放大缩小功能
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
i=i+4;
Font f1=new Font("CHINESE_GB2312",Font.PLAIN,i);//设置字体
t.setFont(f1);
t.setText("王睿");
}
if(e.getSource()==b2){
i=i-4;
Font f1=new Font("CHINESE_GB2312",Font.PLAIN,i);
t.setFont(f1);
t.setText("王睿");
}
}
public void windowClosing(WindowEvent e){
System.exit(0);
}
}