简体   繁体   中英

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

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

    ... 
}

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

Example:

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

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.

我不认为你需要明确删除,java在大多数情况下需要注意,我现在要做的就是不用担心,如果内存泄漏那么你可以使用像JProfiler这样的专用软件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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