Java 创建一个简易计算机启示代码
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorTest {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.loadFrame();
}
}
class Calculator extends Frame {
Button button;
Label label;
TextField textField,textField1,textField2;
Frame frame;
void loadFrame(){
frame = new Frame("计算器");
label = new Label("+");
textField = new TextField(10);
textField1 = new TextField(10);
textField2 = new TextField(20);
button = new Button("=");
button.addActionListener(new MyactionLinstener(this));
frame.setLayout(new FlowLayout());
frame.add(textField);
frame.add(label);
frame.add(textField1);
frame.add(button);
frame.add(textField2);
frame.pack();
frame.setVisible(true);
}
}
class MyactionLinstener implements ActionListener{
Calculator calculator;
public MyactionLinstener(Calculator calculator) {
this.calculator = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(calculator.textField.getText());
int num2 = Integer.parseInt(calculator.textField1.getText());
calculator.textField.setText("");
calculator.textField1.setText("");
calculator.textField2.setText(""+(num1+num2));
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/59ddf8492d0bd5421437b2f7d0437911.png#pic_center)