有个小问题请教
Java code
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
MFrame f=new MFrame("事件监听",100,100);
Monitor m=new Monitor();
Button b1=new Button("start");
Button b2=new Button("stop");
b1.addActionListener(m);
b2.addActionListener(m);
//b1.setActionCommand("f");
//b2.setActionCommand("q");
f.add(b1);
f.add(b2);
}
}
class MFrame extends Frame{
public MFrame(String title,int width,int height){
setLayout(new FlowLayout());
setTitle(title);
setSize(width,height);
setLocation(100,100);
setVisible(true);
}
}
class Monitor implements ActionListener{
public void actionPerformed(ActionEvent e) {
//System.out.println("game will "+e.getActionCommand());
Button b=(Button)e.getSource();
******** if(b==b1)System.out.println("wo");
else System.out.println("ni");
}
}
*******行出错,错在哪里?先谢谢各位了
------解决方案--------------------if(b.getLabel().equals(b1.getLabel())
------解决方案--------------------你的b1是局部变量,在monitor里面访问不到
------解决方案--------------------你是在一个文件里定义了三个CLASS,这和你在三个文件里定义三个CLASS类似,Monitor这个类不可以直接引用Test里面的变量,你可以将二个BUTTON作为变量传入,代码如下
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
MFrame f=new MFrame("事件监听",100,100);
Button b1=new Button("start");
Button b2=new Button("stop");
Monitor m=new Monitor(b1,b2);
b1.addActionListener(m);
b2.addActionListener(m);
//b1.setActionCommand("f");
//b2.setActionCommand("q");
f.add(b1);
f.add(b2);
}
}
class MFrame extends Frame{
public MFrame(String title,int width,int height){
setLayout(new FlowLayout());
setTitle(title);
setSize(width,height);
setLocation(100,100);
setVisible(true);
}
}
class Monitor implements ActionListener{
Button b1=null;
Button b2=null;
public Monitor(Button b1,Button b2){
this.b1=b1;
this.b2=b2;
}
public void actionPerformed(ActionEvent e) {
//System.out.println("game will "+e.getActionCommand());
Button b=(Button)e.getSource();
if(b==b1)System.out.println("wo");
else System.out.println("ni");
}
}
------解决方案--------------------if(b.getLabel().equals(b1.getLabel())
祝楼主中秋节快乐