Java 如何删除 JTextField 上的 MouseListener / ActionListener
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2627946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove MouseListener / ActionListener on a JTextField
提问by mithun1538
I have the following code adding an ActionListener to a JTextField:
我有以下代码将 ActionListener 添加到 JTextField:
chatInput.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
chatInputMouseClicked(evt);
}
});
Now how do I remove this MouseListener using chatInput.removeMouseListener()
, since this function needs an argument?
现在我如何使用 删除这个 MouseListener chatInput.removeMouseListener()
,因为这个函数需要一个参数?
采纳答案by Roman
You can consider 3 approaches:
您可以考虑 3 种方法:
1) Save reference to your listener before adding it so you can remove it later:
1)在添加之前保存对您的听众的引用,以便您以后可以删除它:
MouseListener ml = new MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
chatInputMouseClicked(evt);
}
};
chatInput.addMouseListener (ml);
...
chatInput.removeMouseListener (ml);
2) You can get all certain event listeners with correspondent methods like:
2)您可以使用相应的方法获取所有某些事件侦听器,例如:
public MouseListener[] getMouseListeners()
or
或者
public EventListener[] getListeners(Class listenerType)
Here are the javadocs for the firstand secondmethods. If you can identify among all listeners the one which you want to remove or if you want to remove all listeners this approach may help.
以下是第一种和第二种方法的 javadoc 。如果您可以在所有侦听器中确定要删除的侦听器,或者如果您想删除所有侦听器,则此方法可能会有所帮助。
3) You can use some boolean variable which will 'turn off' your listener. But you should notice that the variable should be a field of outer class:
3)您可以使用一些布尔变量来“关闭”您的侦听器。但是你应该注意到变量应该是外部类的一个字段:
private boolean mouseListenerIsActive;
public void doSmthWithMouseListeners () {
mouseListenerIsActive = true;
chatInput.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (mouseListenerIsActive) {
chatInputMouseClicked(evt);
}
}
});
}
public void stopMouseListner () {
mouseListenerIsActive = false;
}
I would prefer the third one because it gives some flexibility and if I want to turn on mouse listener again I will not need to create new object.
我更喜欢第三个,因为它提供了一些灵活性,如果我想再次打开鼠标侦听器,我将不需要创建新对象。