import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//简易计算器
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField field1;
TextField field2;
TextField field3;
public void loadFrame() {
//3个文本框
field1 = new TextField(10);//字符数
field2 = new TextField(10);//字符数
field3 = new TextField(20);//字符数
//1个按钮
Button button = new Button("=");
//按钮添加事件
button.addActionListener(new MycalculatorListener(this));
//1个标签
Label label = new Label("+");
//布局
setLayout(new FlowLayout());
add(field1);
add(label);
add(field2);
add(button);
add(field3);
pack();
setVisible(true);
}
}
//改为内部类更为简洁
//监听器类
class MycalculatorListener implements ActionListener{
//获取计算器这个对象,在一个类中组合另外一个类
Calculator calculator = null;
//获取三个变量
public MycalculatorListener(Calculator calculator){
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
//1. 获得加数和被加数
//field1.getText()为String类型
int n1 = Integer.parseInt(calculator.field1.getText());
int n2 = Integer.parseInt(calculator.field2.getText());
//2. 将这个值加法运算后,放到第三个框
calculator.field3.setText("" + (n1 + n2));
//清除前两个框
calculator.field1.setText("");
calculator.field2.setText("");
}
}