Howto remove Listeners on SWING JComponents
is there an easy way to remove all Listeners from a JComponent?
JComponent widget = getComponentOverScaryMethod();
EventListener[] listners = widget.getListeners(EventListener.class);
for (E开发者_开发问答ventListener l : listners) {
widget.remove*RandomListener*(l);
}
Background:
I have a JComponent with an unknown amount of Listeners (random types). Since the widget should be removed from the visible part (and won't be needed again) it should be destroyed (and the Listeners should be deleted).
Thanks in advance Joan
There's a workaround mentioned here:
- Bug ID: 4380536, I want a method to remove all listeners from a Component
if you remove the widget from the parent it should never be triggered for events again and the listeners should be freed automatically by gc
the only reason listeners wouldn't get freed is by a leak that keeps the widget reachable even when it shouldn't be
I ran into a comparable problem myself and tried to find more helpful documentation about this slippery seeming issue. On this page someone mentions the possibility of overwriting the subclass to achieve listener deletion. http://www.jguru.com/faq/view.jsp?EID=72457
quote: "Starting at JDK1.02 ...if one is talking about a instance of a component one could always subclass the component and override and keep track of them after calling super methods respectively.
Then you could remove them yourself anytime you want."
Code example included although it seems like a tough one to crack, good luck!
精彩评论