代码及注释
package 简易计算器;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
//创建一个BasicCaculater(基础计算器)类,继承JFrame类,实现ActionListener接口
public class BasicCaculater extends JFrame implements ActionListener{
//一、创建各个控件,控件的声明不能在函数内部进行,否则退出函数后控件不能使用
JTextField outputField = new JTextField(100);
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton buttonPlus = new JButton("+");
JButton buttonEqual = new JButton("=");
JButton buttonClear = new JButton("CE");
//构造函数,在主函数中创建对象时会调用此函数
public BasicCaculater() {
//1、设置界面名字、坐标、大小、关闭方法、界面可见、添加布局管理器
this.setTitle("简易计算器");
this.setBounds(100, 100, 450, 350);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setLayout(null);//设置为自定义
//2、设置组件坐标、大小
outputField.setBounds(20, 20, 400, 50);
outputField.setText("0");//设置文本框默认显示为“0”
outputField.setEditable(false);//禁止从键盘输入信息,只能通过内部程序改变
button1.setBounds(20, 90, 100, 50);
button2.setBounds(140, 90, 100, 50);
buttonPlus.setBounds(20, 160, 100, 50);
buttonEqual.setBounds(140, 160, 100, 50);
buttonClear.setBounds(260, 160, 100, 50);
//3、添加组件
this.add(button1);
this.add(button2);
this.add(buttonPlus);
this.add(buttonClear);
this.add(outputField);
//二、注册事件处理器
button1.addActionListener(this);
button2.addActionListener(this);
buttonPlus.addActionListener(this);
buttonEqual.addActionListener(this);
buttonClear.addActionListener(this);
}
//三、实现事件处理
@Override
public void actionPerformed(ActionEvent e) {
//反应1,在控制台Console中打印命令名(ActionCommand),与按钮名一致
System.out.println("收到事件:"+e.getActionCommand());
//反应2,在输出文本框中显示该命名名
outputField.setText(e.getActionCommand());
}
//四、主函数里面创建对象,一般先创建
public static void main(String[] args) {
BasicCaculater caculater = new BasicCaculater();
}
}
运行结果