新手求助关于this的问题
java吧
全部回复
仅看楼主
level 1
一段程序:
public class TestBox implements ActionListener {
//JButton button;
//JFrame frame;
public static void main(String[] args) {
TestBox box = new TestBox();
box.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("click me");
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
button.setText("I've been clicked!");
}
}
运行后,点击button后异常:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
button cannot be resolved
但如果在类中声明了frame或button(去掉实例变量注释任意一行),程序运行没问题,请问各位大神这是为什么?
2014年06月29日 09点06分 1
level 1
求教
2014年06月30日 09点06分 2
level 8
这个得批评一下你才行,你java是速成的吗?都学到图形界面了,难道还不知道在另一个方法里使用button.setText,button至少要定义成实例变量吧。也就是需要你注释掉的那行JButton button;事实上按你的写法,根本就连编译都不能通过吧?
2014年06月30日 10点06分 3
啊,了解了。不过您猜得真准,我这java真是刚看了还没一周,经您指点才看到问题所在
2014年06月30日 14点06分
1