This post is a bit outdated, but nonetheless.
If you initialize the form as follows:
JFrame firstForm = new JFrame();
firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);
firstForm.setVisible(true);
And, for example, create or open another form with the button:
JFrame secondForm = new JFrame();
secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);
secondForm.setVisible(true);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
This will destroy and destroy the first window without exiting the program.
The key is to install setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE).
It also raises events (I tested it with an event WindowClosing).
source
share