简体   繁体   English

如何删除 SWING JComponents 上的侦听器

[英]Howto remove Listeners on SWING JComponents

is there an easy way to remove all Listeners from a JComponent?有没有一种简单的方法可以从 JComponent 中删除所有侦听器?

JComponent widget = getComponentOverScaryMethod();
EventListener[] listners = widget.getListeners(EventListener.class);
for (EventListener l : listners) {
    widget.remove*RandomListener*(l);
}

Background:背景:

I have a JComponent with an unknown amount of Listeners (random types).我有一个带有未知数量的侦听器(随机类型)的 JComponent。 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提前感谢琼

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如果您从父级中删除小部件,则不应再次触发事件,并且 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 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.引用:“从 JDK1.02 开始......如果谈论组件的实例,则始终可以将组件子类化并在分别调用超级方法后覆盖和跟踪它们。

Then you could remove them yourself anytime you want."然后,您可以随时自行移除它们。”

Code example included although it seems like a tough one to crack, good luck!包含的代码示例虽然看起来很难破解,但祝你好运!

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

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