如何在JTextField上删除MouseListener / ActionListener [英] how to remove MouseListener / ActionListener on a JTextField

查看:129
本文介绍了如何在JTextField上删除MouseListener / ActionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将ActionListener添加到JTextField:

I have the following code adding an ActionListener to a JTextField:

chatInput.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
       chatInputMouseClicked(evt);
    }
});

现在如何使用 chatInput.removeMouseListener()删除此MouseListener ,因为这个函数需要一个参数?

Now how do I remove this MouseListener using chatInput.removeMouseListener(), since this function needs an argument?

推荐答案

你可以考虑3种方法:

1)在添加之前保存对您的监听器的引用,以便稍后将其删除:

1) Save reference to your listener before adding it so you can remove it later:

MouseListener ml = new MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        chatInputMouseClicked(evt);
    }
};
chatInput.addMouseListener (ml);
...
chatInput.removeMouseListener (ml);






2)你可以获得所有特定的事件监听器通讯方法如:


2) You can get all certain event listeners with correspondent methods like:

public MouseListener[] getMouseListeners()  

public EventListener[] getListeners(Class listenerType)

以下是首先第二种方法。
如果您可以在所有侦听器中识别要删除的侦听器,或者如果要删除所有侦听器,则此方法可能会有所帮助。

Here are the javadocs for the first and second methods. 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)您可以使用一些布尔变量来关闭您的监听器。但是你应该注意到变量应该是外部类的字段:

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:

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.

这篇关于如何在JTextField上删除MouseListener / ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆