Search code examples
javaswingawtjbuttonactionlistener

Remove an ActionListener from JButton


I want to remove the action listener from a JButton. But I have an ActionListener like this:

btn.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
          btn.removeActionListener();
     }
});

But the btn.removeActionListener(); needs parameters inside the parenthesis so I'm a little stumped.


Solution

  • Get the ActionListener.

    If you read the AbstractButton API, the JButton has a public ActionListener[] getActionListeners(), which gives you an array of listeners. Get them (there is probably only one), and then remove it (or them if more than one -- using a for-loop) from the button.

    For example

    ActionListener[] listeners = btn.getActionListeners();
    for (ActionListener listener : listeners) {
        btn.removeActionListener(listener);
    }
    

    Having said that, I'm wondering if this might be XY Problem where a better solution is by going with a different approach. Perhaps you just need to put a boolean statement within the listener, and vary its behavior (the code that it calls) depending on the state of a flag (boolean field) within the class.