对象不能被解析

问题描述:

我有这样的代码:对象不能被解析

public class Window extends JFrame { 
public Window(){ 
    ... 

    JButton button = new JButton("OK"); 
    getContentPane().add(button); 

    ButtonHandler handler = new ButtonHandler(); 
    button.addActionListener(handler); 
    ... 
} 

private class ButtonHandler implements ActionListener { 

    public void actionPerformed(ActionEvent event){ 

     if (event.getSource() == button){ // <--- "button can not be resolved" 
      System.out.println("Hello"); 

     }    
    } 
} 

我得到这个错误在Eclipse中。我只是做了一本书中的(简化的)例子,不知道什么是错的。需要知识眼睛! :)

+1

顺便说一句,这可能会产生混淆它的一个父的名字来命名的一类。 http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html – trashgod 2010-03-09 04:20:00

避免依赖于按下哪个按钮。如果对不同的按钮有不同的操作,则为每个操作定义一个单独的ActionListener。

这样你的监听器就不需要检查按下了哪个按钮。

public void actionPerformed(ActionEvent event){ 

    System.out.println("Hello"); 
} 

button对象在类ButtonHandler中不可见;它在Window构造函数中是本地的。您可以将其设置为Window中的一个字段,或者从ActionEvent找出预期的命令。有关更多信息,请参阅tutorial

附录:例如,具有您的ActionListener行动

if ("OK".equals(event.getActionCommand())) { ... 
+1

认为你的意思是它不可见类ButtonHandler – objects 2010-03-09 03:24:44

+0

谢谢!答复修正。 – trashgod 2010-03-09 04:17:50

使按钮处理程序不知道哪个按钮正在响应,但这会阻止您使用同一个对象。

作出新的构造函数的按钮目标为重点

//... 
ButtonHandler handler = new ButtonHandler(button); 
//... 

然后

private class ButtonHandler implements ActionListener { 
    private JButton button; 

    ButtonHandler(JButton button) { this.button = button; } 

    public void actionPerformed(ActionEvent event){ 

    if (event.getSource() == button){ // <--- "button can not be resolved" 
     System.out.println("Hello"); 

    }     
}