英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论