前几天翻了一下课本中的《图形用户界面设计》一章,进而对该部分产生了浓厚的兴趣。在阅读了前几章后,我将课本上关于“加法运算器”的代码运行了一遍:
import java.awt.*;
public class AddFrame extends Frame {
public AddFrame(){
//以下设置框架的标题、尺寸、位置、背景色、布局等属性
super("加法运算");
this.setSize(400 , 100); //设置框架标题
this.setLocation(300 , 400); //设置组件尺寸
this.setLayout(new FlowLayout()); //设置组件的显示位置
//以下在框架上添加标签、文本行、按钮等组件
this.add(new TextField("10" , 8)); //添加文本行(初值,宽度)
this.add(new Label("+")); //添加标签组件
this.add(new TextField("20" , 8));
this.add(new Button("=")); //添加按钮(标题)
this.add(new TextField(10));
this.setVisible(true); //添加框架,必须在添加组件后
}
public static void main(String[] args) {
new pta.AddFrame();
}
}
运行结果如下:
看起来很完美,对吧?实际上,这只是一个框架:比如,你点那个“=”按钮,它并不会进行运算操作;甚至你点“x”号,它也不会退出程序。总而言之,这只是一个美丽的框架。那么,要真的实现一个真正的加法运算器,又该添加什么操作呢?
实际上,这个代码缺乏一定的事件处理方法。在翻看了相关的章节之后,我参照课本,反复进行修改,最后终于实现了一个真正的加法器!
import java.awt.*;
import java.awt.event.*;
class WinClose implements WindowListener {
public void windowClosing(WindowEvent event) { //关闭窗口时执行的事件处理方法
System.exit(0); //结束程序运行
}
public void windowOpened(WindowEvent event) { //打开窗口后执行
}
public void windowActivated(WindowEvent event) { //激活窗口后执行
}
public void windowDeactivated(WindowEvent event) { //变为不活动窗口后执行
}
public void windowIconified(WindowEvent event) { //窗口最小化后执行
}
public void windowDeiconified(WindowEvent event) { //窗口恢复后执行
}
public void windowClosed(WindowEvent event) { //关闭窗口后执行
}
}
public class AddWoker extends Frame implements ActionListener{
private TextField text_Add1 , text_Add2 , text_Result; //显示两个加数以及和的文本行
private Button button_Result; //进行加法操作的按钮
public AddWoker(){
super("加法器");
this.setBounds(300 , 240 , 400 , 100); //位置和尺寸
this.setBackground(Color.lightGray); //设置背景颜色
this.setLayout(new FlowLayout()); //选择流布局
this.text_Add1 = new TextField(8);
this.add(this.text_Add1); //文本行组件
this.add(new Label("+"));
this.text_Add2 = new TextField(8);
this.add(this.text_Add2);
this.button_Result = new Button("=");
this.add(this.button_Result);
this.add(this.text_Result = new TextField(8));
this.button_Result.addActionListener(this); //按钮注册动作事件监听器,委托this对象处理事件
this.setVisible(true);
this.addWindowListener(new WinClose()); //框架注册窗口事件监听器,委托WinClose对象处理事件
}
//动作事件处理方法,实现ActionListener接口
//单击按钮和文本行时触发执行,event.getSource()返回单击的那个按钮(事件源组件)
public void actionPerformed(ActionEvent event){
if(event.getSource() == this.button_Result){
String add1 = this.text_Add1.getText(); //获得文本行字符串
String add2 = this.text_Add2.getText();
int result = Integer.parseInt(add1) + Integer.parseInt(add2);
String Result = String.valueOf(result);
this.text_Result.setText(Result);
}
}
public static void main(String[] args) {
new AddWoker();
}
}
运行结果如下: