package Text;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator {
public static void main(String[] args) {
CalculatorFrame calculatorFrame = new CalculatorFrame();
close(calculatorFrame);
}
//关闭windows窗口
private static void close(Frame frame) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//计算器窗体
class CalculatorFrame extends Frame {
public CalculatorFrame() {
new Frame();
//三个文本框
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(11);
//一个按钮
Button button = new Button("=");
button.addActionListener(new CalculatorListener(num1, num2, num3));
//一个标签
Label label = new Label("+");
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
setVisible(true);
pack();
}
}
//等于按钮加法响应事件
class CalculatorListener implements ActionListener {
//传入num1,num2,num3
private TextField num1, num2, num3;
public CalculatorListener(TextField num1, TextField num2, TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
//取出num1和num2的字符串转换成整形int后相加
int num = Integer.parseInt(num1.getText()) + Integer.parseInt(num2.getText());
//相加后将结果填入num3
num3.setText("" + num);
}
}
运行结果如下: