【问题标题】:Object can not be resolved对象无法解析
【发布时间】:2010-03-09 02:56:00
【问题描述】:

我有这个代码:

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 中遇到了这个错误。我只是在书中找到了一个(简化的)示例,不知道有什么问题。需要知识的眼睛! :)

【问题讨论】:

标签: java listeners


【解决方案1】:

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

附录:例如

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

【讨论】:

  • 认为你的意思是它对 ButtonHandler 类不可见
【解决方案2】:

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

这样你的听众就不需要检查按下了什么按钮。

public void actionPerformed(ActionEvent event){

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

【讨论】:

    【解决方案3】:

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

    新建一个构造函数,以按钮对象为键

    //...
    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");   
    
        }                  
    }  
    

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多