简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM