import java.awt.*;
import java.awt.event.*;public class TestMath {
public static void main(String[] args) {
new TFFrame().launchFrame();
}
}class TFFrame extends Frame {
TextField num1, num2, num3;
public void launchFrame() {
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(15);
Label lblPlus = new Label("+");
Button btnEqual = new Button("=");
btnEqual.addActionListener(new MyMonitor(this));
setLayout(new FlowLayout());
add(num1);
add(lblPlus);
add(num2);
add(btnEqual);
add(num3);
pack();
setVisible(true);
}
}class MyMonitor implements ActionListener {
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));

}
}
这两句什么意思,有什么用?
TFFrame tf = null;

public MyMonitor(TFFrame tf) {
this.tf = tf;
}

解决方案 »

  1.   

    TFFrame tf = null;//声明一个变量,同时初始化为null(空值)//构造方法
    public MyMonitor(TFFrame tf) {
    this.tf = tf;//注意我的着色,红的对应红的,蓝的对应蓝的
    }
      

  2.   

    因为要让MyMonitor类和TFFrame类关联,也就是说,要让MyMonitor能操作TFFrame的成员,那么MyMonitor就要知道有TFFrame一个对象存在,怎样才能知道呢,就是在MyMonitor类定义一个TFFrame成员,然后通过构造函数,让该成员指向实际的TFFrame对象,这样就有了TFFrame tf = null; //定义成员public MyMonitor(TFFrame tf) {
    this.tf = tf; //让成员指向实际的TFFrame对象
    }
      

  3.   


    actionListener是一个监听器TFFrame tf = null; //定义一个TFFrame类型的对象,设为null//带参数的构造方法,给成员变量tf赋值引用
    public MyMonitor(TFFrame tf) {
    this.tf = tf;
      

  4.   

    因为要让MyMonitor类和TFFrame类关联,也就是说,要让MyMonitor能操作TFFrame的成员,那么MyMonitor就要知道有TFFrame一个对象存在,怎样才能知道呢,就是在MyMonitor类定义一个TFFrame成员,然后通过构造函数,让该成员指向实际的TFFrame对象,这样就有了TFFrame tf = null; //定义成员public MyMonitor(TFFrame tf) {
    this.tf = tf; //让成员指向实际的TFFrame对象
    }
    this 表示当前的对象,就是你这个类所在的对象