This Java tutorial shows how to change the default close action to exit the application when the window is closed. In additon, this tutorial discusses the different close actions.
When a JFrame is closed, the default behavior is to hide the window when the user clicks on the close box. There are four different actions that can be performed when the window is closed. These actions are defined in the interface javax.swing.WindowConstants which is implemented by JFrame.
- DISPOSE_ON_CLOSE - Dispose the window when closed.
- DO_NOTHING_ON_CLOSE - Do nothing when the window is closed.
- EXIT_ON_CLOSE - Exit the application when the window is closed.
- HIDE_ON_CLOSE - Hide the window when the window is closed.
To change the default close action on a JFrame, it is done by simply calling the setDefaultCloseAction() method on a JFrame. The following example shows how to change the default close action:
JFrame myFrame = new JFrame();