Close a Window in Java
This article will show you how to close a window in Java. Closing a window is much easier using Swing's JFrame, but it's also doable using AWT's Frame.
Steps
Using javax.swing.JFrame
- Obtain an instance of a
JFrame, or create a new one. - Set default close operation. Default close operation is set using the setter method inside the
JFrameclasssetDefaultCloseOperationthat determines what happens when the close button is clicked and takes the following parameters:WindowConstants.EXIT_ON_CLOSE- Closes the frame and terminates the execution of the program.WindowConstants.DISPOSE_ON_CLOSE- Closes the frame and does not necessarily terminate the execution of the program.WindowConstants.HIDE_ON_CLOSE- Makes the frame appear like it closed by setting its visibility property to false. The difference betweenHIDE_ON_CLOSEandDISPOSE_ON_CLOSEis that the latter releases all of the resources used by the frame and its components.WindowConstants.DO_NOTHING_ON_CLOSE- Does nothing when the close button is pressed. Useful if you wish to, for example, display a confirmation dialog before the window is closed. You can do that by adding aWindowListenerto the frame and overridingwindowClosingmethod. Example of the custom close operation:
- Obtain an instance of a
Frame, or create a new one. - Add window listener. Call
addWindowListenermethod on the instance. The required argument isWindowListener. You can either implement every method of theWindowListenerinterface or override only the methods you need fromWindowAdapterclass. - Handle window closing event. Implement
windowClosingmethod fromWindowListenerinterface or override it fromWindowAdapterclass. There are two ways of closing a window:- Dispose the window after the close button is clicked:
- Call
disposemethod insidewindowClosingmethod.
- Call
- Terminate the program after the close button is clicked:
- Call
System.exitmethod insidewindowClosingmethod.
- Call
- Dispose the window after the close button is clicked:
</ol>
Using java.awt.Frame
</ol>
Tips
- Swing is preferred over AWT since the latter is really outdated.
- Using
WindowAdapteryou don't have to implement each and every methodWindowListenercontract tells us to, but only the ones we need.
Related Articles
- Download Java to Internet Explorer
- Check Null in Java
- Create a New Java Project in Eclipse
- Get the Length of a String in Java