package Lesson2;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestCalc {
public static void main(String[] args) {
Calculator calculator = new Calculator("只能计算加法的废物计算器");
}
}
class Calculator extends Frame{
public Calculator(String title) {
this.setTitle(title);
setLayout(new FlowLayout());
TextField textField1 = new TextField(10);
TextField textField2 = new TextField(10);
TextField textField3 = new TextField(11);
Label label = new Label("+");
Button buttonC = new Button("C");
Button button = new Button("=");
button.addActionListener(new Equal(textField1, textField2, textField3));
buttonC.addActionListener(new Clear(textField3));
add(buttonC);
add(textField1);
add(label);
add(textField2);
add(button);
add(textField3);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class Equal implements ActionListener{
private TextField textField1, textField2, textField3;
public Equal(TextField textField1, TextField textField2, TextField textField3) {
this.textField1 = textField1;
this.textField2 = textField2;
this.textField3 = textField3;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(textField1.getText());
int n2 = Integer.parseInt(textField2.getText());;
textField3.setText("" + (n1 + n2));
textField1.setText("");
textField2.setText("");
}
}
class Clear implements ActionListener{
private TextField textField;
public Clear(TextField textField) {
this.textField = textField;
}
@Override
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
}
加法计算器(个人留档)
于 2023-04-13 14:55:31 首次发布