In java, can I change the reference to a listener after the object is constructed?
for example, Can I change the listener using its setter when an object of this class is instantiated?
If I can’t, how can I do that, I mean changing the listener whenever I needed?
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();
}
}
Sure you can add, remove ActionListeners, but not as you’re trying. If you change the ActionListener referenced to by the listener variable, this will have no effect on the one that has been added to the JButton. You must specifically add or remove listeners to the JButton via its
addActionListener(...)andremoveActionListener(...)methods to have this effect. I think that the key point that you need to understand is that the listener variable is not the same as the ActionListener object that it might refer to. All this variable does is refer to an ActionListener object if one has been given to it. It has absolutely no effect on the ActionListener that may or may not be listening to the JButton.By the way, your current code appears to be trying to add
nullas the JButton’s ActionListener since it the listener variable null at the time it is added to the button in the class’s constructor:Perhaps instead you want to do this:
or if you want your listener added in place of all existing ActionListeners
You also can set the JButton’s Action if you prefer to use AbstractActions, and some feel that this is a cleaner way to go about this.