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

  1. Obtain an instance of a JFrame, or create a new one.
  2. Set default close operation. Default close operation is set using the setter method inside the JFrame class setDefaultCloseOperation that 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 between HIDE_ON_CLOSE and DISPOSE_ON_CLOSE is 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 a WindowListener to the frame and overriding windowClosing method. Example of the custom close operation:
  3. </ol>

    Using java.awt.Frame

    1. Obtain an instance of a Frame, or create a new one.
    2. Add window listener. Call addWindowListener method on the instance. The required argument is WindowListener. You can either implement every method of the WindowListener interface or override only the methods you need from WindowAdapter class.
    3. Handle window closing event. Implement windowClosing method from WindowListener interface or override it from WindowAdapter class. There are two ways of closing a window:
      • Dispose the window after the close button is clicked:
      • Terminate the program after the close button is clicked:
    4. </ol>

      Tips

  • Swing is preferred over AWT since the latter is really outdated.
  • Using WindowAdapter you don't have to implement each and every method WindowListener contract tells us to, but only the ones we need.

Related Articles