1

I have an ArrayList of JFrames and I want to be able to detect when all the windows are closed, and thus end the program.

So far every time I make a JFrame, I add it to the Array List. I also implemented a WindowListener, and remove that JFrame from the List whenever windowClosing() is called.

My problem, however, is that the program does not end when the List is empty. Usually, I use frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), but now I have multiple windows and that won't work. Should I just manually call System.Exit(0); or is there a more preferred way of terminating the program.

Thanks

Sample

public class MainFrame extends JFrame{

private static final ArrayList<MainFrame> frameList = new ArrayList<MainFrame>();

public static void main(String[] args){
    newFrame();
    newFrame();
    newFrame();
}

public MainFrame(){     
    addWindowListener(new Listener());
    setSize(800, 600);
    setVisible(true);
}

class Listener implements WindowListener{
    public void windowClosing(WindowEvent arg0) {
        frameList.remove(MainFrame.this);
        if(frameList.size() == 0){
             //End Program
        }
    }
}

public static void newFrame() {
    frameList.add(new MainFrame());
}   

}

Jtvd78
  • 4,135
  • 5
  • 20
  • 21

1 Answers1

2

Basically if you change defaultCloseOperation to DISPOSE_ON_CLOSE, this will cause the window to release it's reference to the native peer when it's closed and when all the peers are free, the JVM will exit automatically

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainFrame extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                newFrame();
                newFrame();
                newFrame();
            }
        });
    }

    public MainFrame() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(800, 600);
        setVisible(true);
    }

    public static void newFrame() {
        new MainFrame();
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366