Recursion causes exit to exit all JFrames (terminates app)
Question
I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window.
How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance?
Here is the relevant code:
[...]
JMenuItem newMenuItem = new JMenuItem ("New");
newMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new MainWindow();
}
});
fileMenu.add(newMenuItem);
[....]
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
fileMenu.add(exit);
[...]
Solution 2
I completely removed the frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE);
code.
I changed it to DISPOSE_ON_CLOSE
and still the problem was still happening. I ended up creating a windowEvent and adding: frame.dispose();
and the behavior is what I wanted.
Here is the code:
frame.addWindowListener(new WindowListener() {
public void windowClosing(WindowEvent e) {
//Allows for multiple instances and properly closing
//only one of the Frames instead of all of them
frame.dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
});
OTHER TIPS
First you should try JFrame.DISPOSE_ON_CLOSE
instead of JFrame.EXIT_ON_CLOSE
because EXIT_ON_CLOSE shuts down the application no matter if there are active threads running or not.
If you still have issues you should consider to introduce an instance counter. To react smarter
See also this discussion