views:

380

answers:

1

Hello everyone,

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);
    }
});

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

+3  A: 

You can consider 3 approaches:

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) You can get all certain event listeners with correspondent methods like:

public MouseListener[] getMouseListeners()  

or

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) 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.

Roman
I usually use the first option to permanently remove a listener from a component that lives longer that the one which registered the listener (e.g. in a `dispose()` method).To temporarily disable a listener, I have used the third option. This is mostly required to prevent recursion. E.g. when a listener that triggers on text changes leads to a change in that same text (for whatever reason), I disable the listener at the start of its listening method and enable it at the end.
Christian Semrau
I guess I have to create a MouseListener before using it. I cant remove anonymous MouseListeners.
mithun1538