There are many subjects one has to know when working with Swing and one of them is window closing. A beginner pass through some steps (and yes, I consider myself a beginner in Swing) and here are those I experienced myself.
Hiding is default
In the first step, you realize that by clicking the cross in the title bar, the window only disappears. It’s not disposed of, and if it’s your main application’s window, that’s bad because it means you’ve lost any handle on the underlying running JVM. It means users just keep spawning new JVMs when launching the application and do not close them, using more and more of the platform memory.
By then, you learn that any Swing JFrame can be set the right close operation by calling its
setDefaultCloseOperation() method. This let you choose the behavior when closing the window: for example,
WindowConstants.EXIT_ON_CLOSE exits the JVM when closing the window. This should be set of course on your main window.
This method has a slight disadvantage, however. What if we need to do some cleaning operations before exiting the JVM? There’s something called shutdown hooks that the JVM calls just before exiting. It already is explained in this post and fits our needs… provided what we need to do is related to the entire application.