After discussing the startup in the last post I continue on the shutdown of a Java application. Typically when the application frame (or window) closes the user is asked if he really wants to exit. If he commits this the application exits while closing the application. In the other case the application might restart or do nothing. How can this be handled with Java Swing?
A common way of shutdown implementation is to add an implementation of WindowListener to the application frame and react on the events. The listener already has a callback windowClosing(WindowEvent) which is called before the window closes. Here the application might ask the user if he really wants to exit or just clicked the wrong button ;-). In most cases if the user commits a common implementation is to invoke System.exit(0) because this terminates the JVM but the JFrame class provides a more convinient approach. Simply set the default closing operation to JFrame.EXIT_ON_CLOSE will do the same job. If the application requires a callback that the application frame is really closed simply set the closing operation to JFrame.DISPOSE_ON_CLOSE and implement the listeners windowClosed(WindowEvent) method. You even don’t need to invoke System.exit(int) because the EDT exits when no window is active. Which means if the application frame is the only window it also exits the application.
This image shows the event invocations when a window is closed. First the user closes the window by pressing the red icon in the top right corner. This causes the EDT to dispatch a window event to the application frame. The event has the type WindowEvent.WINDOW_CLOSING. The application has registered a WindowListener that invokes shutdown in the EDT. In the shutdown method the application asks the user if he really wants to exit. If he aborts the application sets the default close operation to JFrame.DO_NOTHING_ON_CLOSE which continues the application and keeps the frame open. If the user commits the application sets the default close operation to DISPOSE_ON_CLOSE which causes the application frame to be disposed. This again causes the EDT to dispatch a new WindowEvent with the type WindowEvent.CLOSED. Now the application can do some magic in the EDT after the window is closed. If no window exists the EDT exits and the JVM terminates. If the application sets the default close operation to JFrame.EXIT_ON_CLOSE the application will terminate immediately after the windowClosing method is executed (just look at the code of JFrame’s processWindowEvent method).