简体   繁体   English

如何在JTextField上删除MouseListener / ActionListener

[英]how to remove MouseListener / ActionListener on a JTextField

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? 现在如何使用chatInput.removeMouseListener()删除此MouseListener,因为此函数需要参数?

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 first and second methods. 以下是第一种第二种方法的javadoc。 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. 如果您可以在所有侦听器中识别要删除的侦听器,或者如果要删除所有侦听器,则此方法可能会有所帮助。


3) You can use some boolean variable which will 'turn off' your listener. 3)您可以使用一些布尔变量来“关闭”您的监听器。 But you should notice that the variable should be a field of outer class: 但是你应该注意到变量应该是外部类的字段:

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. 我更喜欢第三个,因为它提供了一些灵活性,如果我想再次打开鼠标监听器,我将不需要创建新对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM