In the example below MainFrame creates other JFrames. These newly created frames have DISPOSE_ON_CLOSE set as default close operation. When I click the close button, frames disappear but still are available from Window.getWindows() method. When I open let's say 4 windows, close them and click "Print windows counts" it shows
Windows: 4
How to make them disappear permanently from all Swing resources that aren't controlled by me?
In the real world these frames hold many other references and it causes memory leaks as they are never subject to be garbage collected.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Window;
public class MainFrame extends JFrame {
public static void main(String[] args) {
MainFrame t = new MainFrame();
SwingUtilities.invokeLater(() -> t.setVisible(true));
}
public MainFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton newWindowButton = new JButton("Open window");
newWindowButton.addActionListener((action) -> {
JFrame otherFrame = createChildFrame();
otherFrame.setVisible(true);
});
JButton printWidnowsButton = new JButton("Print windows count");
printWidnowsButton.addActionListener((action) -> {
System.out.println("Windows: " + Window.getWindows().length);
});
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(newWindowButton);
cp.add(printWidnowsButton, BorderLayout.SOUTH);
pack();
}
private JFrame createChildFrame() {
JFrame otherFrame = new JFrame();
otherFrame.setBounds(0, 0, 100, 100);
otherFrame.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
return otherFrame;
}
}