Should I call removeMouseListener ()?

If I added MouseListenerusing Component#addMouseListener()am, am I obligated to remove it using removeMouseListener()?

I think, in particular, with regard to memory leaks, which javax.swing.Timercan cause if stop()not called.

I can’t find anything in the documentation to say that the listeners should be deleted, but maybe I think this is something that the author can accept. May be.

Checking the JDK source suggests that if there are no links in the mouse listeners themselves that would prevent it, the presence of the listener will not prevent the appropriate component from being GC'd.

I believe that given the maxim “it's better than sorry, I'm really asking if someone can point me to some documentation that indicates that it is not necessary to remove mouse listeners or a more general case of any listener.

+5
source share
2 answers

It depends on what other objects contain references to the listener, and whether the listener has a link to the component. I studied Swing code a bit and, as far as I can tell, registrars are listening to strong links to their listeners.

addMouseListener, addMouseListener(new MouseListener()...), . , , .

, - :

public class Foo implements MouseListener {
    ...
    private Component c;
    public void registerWithComponent(final Component c) {
        c.addMouseListener(this);
        this.c = c;
    }
}

, Foo ( ), , , removeMouseListener.

+4

, .

GC Java (, GC'd MouseListener - )

+1

All Articles