This example shows that it is not necessary to remove listener of a component which is being removed from the UI. This is true even for a listener whose reference still lives externally in the active program.
Example
public class ComponentListenersAndGcTest {
public static void main(String[] args) {
JFrame frame = createFrame();
JPanel componentPanel = new JPanel();
JPanel topPanel = new JPanel();
JButton removeAddComponentButton = new JButton("add/remove");
removeAddComponentButton.addActionListener(e -> removeAndAddComponents(componentPanel));
topPanel.add(removeAddComponentButton);
frame.add(topPanel, BorderLayout.NORTH);
frame.add(componentPanel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static int c = 0;
private static final ActionListener listener = (ae) -> System.out.println(ae.getActionCommand());
private static void removeAndAddComponents(JPanel panel) {
panel.removeAll();
for (int i = 0; i < 10000; i++) {
MyButton b = new MyButton(Integer.toString(++c));
b.addActionListener(listener);
panel.add(b);
}
panel.validate();
panel.repaint();
System.gc();
}
private static JFrame createFrame() {
JFrame frame = new JFrame("Listeners GC example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(600, 300));
return frame;
}
private static class MyButton extends JButton {
public MyButton(String text) {
super(text);
}
@Override
protected void finalize() throws Throwable {
System.out.println("button finalized: " + getText());
System.out.println("----------");
}
}
}
Output
Clicking 'add/remove' button each time (except for the first time) will mark the buttons for garbage collection:
When a listener added to the button, its reference is kept within the button internally which is not a criteria for the garbage collection in case if the button is no longer used in the program. If a button's reference is kept outside actively (e.g. in a collection) then it will not be eligible for garbage collection. See also a more basic example for the garbage collection eligibility here.