What\'s the correct way to get a JFrame
to close, the same as if the user had hit the X
close button, or pressed Alt+F4 (on W
If you really do not want your application to terminate when a JFrame is closed then,
use : setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
instead of : setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Here's a synopsis of what the solution looks like,
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
This answer was given by Alex and I would like to recommend it. It worked for me and another thing it's straightforward and so simple.
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
I have tried this, write your own code for formWindowClosing() event.
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int selectedOption = JOptionPane.showConfirmDialog(null,
"Do you want to exit?",
"FrameToClose",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
setVisible(false);
dispose();
} else {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
This asks user whether he want to exit the Frame or Application.
Based on the answers already provided here, this is the way I implemented it:
JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame stuffs here ...
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
The JFrame gets the event to close and upon closing, exits.
Here would be your options:
System.exit(0); // stop program
frame.dispose(); // close window
frame.setVisible(false); // hide window
Not only to close the JFrame but also to trigger WindowListener events, try this:
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));