从JButton移除ActionListener

问题描述

我想从JButton删除动作监听器。但是我有这样的ActionListener

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

但是btn.removeActionListener();在括号内需要参数,所以我有些困惑。

解决方法

获取ActionListener。

如果您读了AbstractButton API,则JButton会有一个public ActionListener[] getActionListeners(),它为您提供了一组侦听器。获取它们(可能只有一个),然后从按钮中将其删除(如果有多个,则使用for循环)。

例如

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

话虽如此,我想知道这是否可能是XY Problem更好的解决方案,那就是采用另一种方法。也许您只需要在侦听器中放置一个布尔语句,并根据类中标志(布尔字段)的状态来改变其行为(它调用的代码)。