从JButton中移除一个ActionListener。

huangapple go评论87阅读模式
英文:

Remove an ActionListener from JButton

问题

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

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

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

英文:

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.

答案1

得分: 2

获取ActionListener。

如果你阅读了AbstractButton API,JButton有一个public ActionListener[] getActionListeners()方法,它会给你一个监听器数组。获取它们(可能只有一个),然后从按钮中移除它(如果有多个,使用for循环)。

例如:

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

话虽如此,我在想这是否可能是一个XY问题,在这种情况下,通过采用不同的方法可能会有更好的解决方案。也许你只需要在监听器内部放置一个布尔语句,并根据类中的标志(布尔字段)的状态来改变其行为(调用的代码)。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月26日 00:30:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64526090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定