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