这句:b1.addActionListener(new MyeventAdd(this));//这里为什么传this,this代表上面,为什么传mtf就错package javagui;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class TestMath { public static void main(String[] args) {
new MyFrameMath().MYMath();
}
}
class MyFrameMath extends Frame{
TextField tf1,tf2,tf3;
public void MYMath(){
tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(15);
Label l = new Label("+");
Button b1 = new Button("=");
setLayout(new FlowLayout());
add(tf1);
add(l);
add(tf2);
add(b1);
add(tf3);
setResizable(false);
pack();
MyFrameMath mtf = new MyFrameMath();
b1.addActionListener(new MyeventAdd(this));//这里为什么传this,this代表上面,为什么传mtf就错呢?
setVisible(true);
}
}
class MyeventAdd implements ActionListener{
MyFrameMath mtf =null;
public MyeventAdd(MyFrameMath mtf){
this.mtf = mtf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(mtf.tf1.getText());
int n2 = Integer.parseInt(mtf.tf2.getText());
mtf.tf3.setText(String.valueOf(n1+n2));
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class TestMath { public static void main(String[] args) {
new MyFrameMath().MYMath();
}
}
class MyFrameMath extends Frame{
TextField tf1,tf2,tf3;
public void MYMath(){
tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(15);
Label l = new Label("+");
Button b1 = new Button("=");
setLayout(new FlowLayout());
add(tf1);
add(l);
add(tf2);
add(b1);
add(tf3);
setResizable(false);
pack();
MyFrameMath mtf = new MyFrameMath();
b1.addActionListener(new MyeventAdd(this));//这里为什么传this,this代表上面,为什么传mtf就错呢?
setVisible(true);
}
}
class MyeventAdd implements ActionListener{
MyFrameMath mtf =null;
public MyeventAdd(MyFrameMath mtf){
this.mtf = mtf;
}
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(mtf.tf1.getText());
int n2 = Integer.parseInt(mtf.tf2.getText());
mtf.tf3.setText(String.valueOf(n1+n2));
}
}
this指的是MyFrameMath对象
因为按钮b1属于当前的MyFrameMath,增加监听的时候只能传入b1所属MyFrameMath
如果你传入的是一个新的MyFrameMath对象就和按钮b1没有关系,无法实现监听
public MyeventAdd(MyFrameMath mtf){
this.mtf = mtf;
}
这是我的理解。