2010-03-09 90 views
1

我有這樣的代碼:對象不能被解析

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

回答

2

避免依賴於按下哪個按鈕。如果對不同的按鈕有不同的操作,則爲每個操作定義一個單獨的ActionListener。

這樣你的監聽器就不需要檢查按下了哪個按鈕。

public void actionPerformed(ActionEvent event){ 

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

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

1

使按鈕處理程序不知道哪個按鈕正在響應,但這會阻止您使用同一個對象。

作出新的構造函數的按鈕目標爲重點

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

    }     
}