Properly closing Swing windows

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.

The basics

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.

Shutdown hook

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.

Window listeners

But how can we release resources that are needed by a popup window before the JVM exits? The last way I found was to use window listeners: by implementing WindowListener (or better, by extending WindowAdapter), one can code the desired behavior easily in the windowClosed() method.

Nicolas Fränkel

Nicolas Fränkel

Nicolas Fränkel is a Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Currently working for Exoscale. Also double as a teacher in universities and higher education schools, a trainer and triples as a book author.

Read More