1

在java中,我可以在构造对象后更改对侦听器的引用吗?例如,当实例化此类的对象时,我可以使用其设置器更改侦听器吗?如果我不能,我该怎么做,我的意思是在需要时更改侦听器?

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();
    }

}
4

1 回答 1

1

当然,您可以添加、删除 ActionListener,但不能像您尝试的那样。如果您更改侦听器变量引用的 ActionListener,这不会影响已添加到 JButton 中的 ActionListener。addActionListener(...)您必须通过其和方法专门添加或删除 JButton 的侦听器removeActionListener(...)才能产生此效果。我认为您需要了解的关键点是侦听器变量与它可能引用的 ActionListener 对象不同。这个变量所做的只是引用一个 ActionListener 对象(如果已经给它一个)。它对可能正在侦听或未侦听 JButton 的 ActionListener 绝对没有影响。

顺便说一句,您当前的代码似乎正试图添加null为 JButton 的 ActionListener,因为它是在将其添加到类的构造函数中的按钮时的侦听器变量 null :

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);
}

或者如果您希望添加您的侦听器来代替所有现有的 ActionListener

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,有些人认为这是一种更简洁的方法。

于 2012-11-19T23:04:45.153 回答