删除actionListener [英] Removing actionListeners

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

问题描述

我正在用Java(J2ME)构建一些GUI,并且对避免与actionListeners有关的资源/内存泄漏的最佳做法有疑问。

I'm building some GUI in Java (J2ME) and have doubts what is the best practice to avoid resource/memory leaks pertaining to actionListeners.

假设我有一个类对象,该类对象的成员变量添加了一个actionListener。我需要在对象超出范围之前显式删除此actionListener吗?通过不删除actionListener,当MyPanel类对象超出范围时,是否会造成内存/资源泄漏?

Let's say I have a class object that has a member variable that adds an actionListener. Do I need to remove this actionListener explicitly before the object goes out of scope? By not removing the actionListener, will I create a memory/resource leak, when the MyPanel class object goes out of scope?

public class MyPanel implements ActionListener
{

    private LabelButton _button;

    public MyPanel()
    {
        _button.addActionListener(this);
    }

    ... 
}


推荐答案

使用 getListeners / getActionListeners ,您可以获取在指定元素上注册的所有监听器,并使用 removeActionListener 您可以从元素中删除监听器

With getListeners / getActionListeners you can get all Listeners registered at a specified element, and with removeActionListener you can remove a Listener from an element

示例:

for(ActionListener act : buttonToBeFreedFromListeners.getActionListeners()) {
    buttonToBeFreedFromListeners.removeActionListener(act);
}

仅需注意:只要您不保存对以下内容的侦听器的引用,在您的元素上注册时,GarbageCollector会在他们选择元素时选择监听器,因为它们是唯一的引用。

Just a note: As long as you do not save references to the Listeners that are registered at your elements, the GarbageCollector will pick up the Listeners when he picks up the elements, as they have the only reference to it.

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

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