从 JButton 中移除一个 ActionListener

Remove an ActionListener from JButton

我想从 JButton 中删除动作侦听器。但是我有一个像这样的ActionListener

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

但是 btn.removeActionListener(); 需要括号内的参数所以我有点难过。

获取 ActionListener。

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

例如

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

话虽如此,我想知道这是否 XY Problem 更好的解决方案是采用不同的方法。也许您只需要在侦听器中放置一个布尔语句,并根据 class.

中标志(布尔字段)的状态改变其行为(它调用的代码)