方法一:(比较繁)
package GUI;
/*通过Frame窗口实现简单的加法运算*/
import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String[] args) {
new TFFrame().lanunFrame();
}
}
class TFFrame extends Frame {
public void lanunFrame() {
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(15);
Label lbplus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor(num1, num2, num3));
setLayout(new FlowLayout());
add(num1);
add(lbplus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
}
class MyMonitor implements ActionListener {
TextField num1, num2, num3;
public MyMonitor(TextField num1, TextField num2, TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());//转成整型计算
int n2 = Integer.parseInt(num2.getText());
num3.setText("" + (n1 + n2));//再将num3转成字符型
}
}
方法二:(持有对方的引用)
package GUI;
/*通过Frame窗口实现简单的加法运算--持有对方的引用*/
import java.awt.*;
import java.awt.event.*;
public class TFMath {
public static void main(String[] args) {
new TFFrame().lanunFrame();
}
}
class TFFrame extends Frame {
TextField num1, num2, num3;
public void lanunFrame() {
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(15);
Label lbplus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor(this));
setLayout(new FlowLayout());
add(num1);
add(lbplus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
}
class MyMonitor implements ActionListener {
// TextField num1, num2, num3;
// public MyMonitor(TextField num1, TextField num2, TextField num3) {
// this.num1 = num1;
// this.num2 = num2;
// this.num3 = num3;
// }
TFFrame tf = null;
public MyMonitor(TFFrame tf) { //持有对方的引用
this.tf = tf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(tf.num1.getText());//转成整型计算
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText("" + (n1 + n2));//再将num3转成字符型
}
}