2012-11-19 126 views
1

在java中,可以在构造对象后将引用更改为侦听器吗? 例如,当这个类的对象被实例化时,我可以使用它的setter来更改侦听器吗? 如果我不能,我该怎么做,我的意思是在需要时改变听众?何时注册侦听器?

public class ListenerTest extends JFrame { 

    ActionListener listener; 

    public ListenerTest() { 

     JPanel jPanel = new JPanel(); 
     JButton jButton = new JButton("Activate!"); 
     jButton.addActionListener(listener); 
     jPanel.add(jButton); 
     add(jPanel); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setTitle("Demo Drawing"); 
     setLocationRelativeTo(null); 
     pack(); 
     setVisible(true); 
    } 

    public ActionListener getListener() { 
     return listener; 
    } 

    public void setListener(ActionListener listener) { 
     this.listener = listener; 

    } 

    public static void main(String[] args) { 
     ListenerTest frame = new ListenerTest(); 
    } 

} 

回答

1

当然,你可以添加,删除ActionListeners,但不是你试图。如果您更改了由侦听器变量引用的ActionListener,则这对于添加到JButton中的ActionListener没有影响。您必须通过其addActionListener(...)removeActionListener(...)方法专门添加或删除JButton的听众才能产生此效果。我认为您需要了解的关键点是listener变量与它可能引用的ActionListener对象不同。所有这个变量都会引用一个ActionListener对象,如果已经给它的话。它对可能会或可能不会听JButton的ActionListener完全没有影响。

顺便说一句,你当前的代码似乎试图在它被添加到该按钮,在类的构造函数时添加null作为JButton的ActionListener的因为它的听众变空:

ActionListener listener; // variable is null here 

public ListenerTest() { 

    JPanel jPanel = new JPanel(); 
    JButton jButton = new JButton("Activate!"); 
    jButton.addActionListener(listener); // variable is still null here! 
    // .... 
} 

public void setListener(ActionListener listener) { 
    this.listener = listener; // this has no effect on the JButton 
} 

也许相反,你要做到这一点:

public void setListener(ActionListener listener) { 
    jButton.addActionListener(listener); 
} 

,或者如果你想在地方所有现有的ActionListeners添加监听

public void setListener(ActionListener listener) { 
    ActionListener[] listeners = jButton.getActionListeners(); 
    for(ActionListener l : listeners) { 
     jButton.removeActionListener(l); // remove all current ActionListeners 
    } 
    // set new ActionListener 
    jButton.addActionListener(listener); 
} 

如果你喜欢使用AbstractActions,你也可以设置JButton的Action,有人认为这是一个更清晰的方法。

+1

+1提及操作。我是“一些”的人之一,他强烈地感觉到使用Actions是一种远远更简洁的方式来配置按钮,菜单等。如果您想禁用按钮,或者在按钮和按钮中共享相同的动作菜单,你想要一个行动。 – user949300

+0

@ user949300:谢谢,你当然是对的。我想你会和kleopatra相处的很好。 –

相关问题