初学java的GUI编程,只支持加法
[Java] 纯文本查看 复制代码 import java.awt.*;
import java.awt.event.*;
public class calculator {
public static void main(String[] args) {
new mycalc();
}
}
class mycalc extends Frame {
public mycalc(){
Button button1 = new Button("compute");
Button button2 = new Button("empty");
TextField textField1 = new TextField(10);
TextField textField2 = new TextField(10);
TextField textField3 = new TextField(10);
Label label1 = new Label("+");
Label label2 = new Label("=");
this.setTitle("计算器");
this.setBackground(new Color(255, 255, 255));
this.setBounds(500,500,236,80);
this.setVisible(true);
this.setLayout(new FlowLayout());
this.add(textField1);
this.add(label1);
this.add(textField2);
this.add(label2);
this.add(textField3);
this.add(button1);
this.add(button2);
this.pack();
mywframe myframe = new mywframe();
this.addWindowListener(myframe);
mybuttonlistener mybuttonlistener = new mybuttonlistener(textField1,textField2,textField3);
button1.addActionListener(mybuttonlistener);
mybutton2listener mybutton2listener = new mybutton2listener(textField1,textField2,textField3);
button2.addActionListener(mybutton2listener);
}
}
class mybuttonlistener implements ActionListener {
private TextField num4;
private TextField num5;
private TextField num6;
public mybuttonlistener(TextField num1,TextField num2,TextField num3){
this.num4 = num1;
this.num5 = num2;
this.num6 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
int num7 = Integer.parseInt(num4.getText());
int num8 = Integer.parseInt(num5.getText());
num6.setText(""+(num7+num8));
}
}
class mybutton2listener implements ActionListener{
private TextField num4;
private TextField num5;
private TextField num6;
public mybutton2listener(TextField num1,TextField num2,TextField num3){
this.num4 = num1;
this.num5 = num2;
this.num6 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
num4.setText("");
num5.setText("");
num6.setText("");
}
}
class mywframe implements WindowListener{
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
} |