Nicolas Frankel is an IT consultant with 10 years experience in Java / JEE environments. He likes his job so much he writes technical articles on his blog and reviews technical books in his spare time. He also tries to find other geeks like him in universities, as a part-time lecturer. Nicolas is a DZone MVB and is not an employee of DZone and has posted 207 posts at DZone. You can read more from them at their website. View Full User Profile

Properly closing Swing windows

01.09.2012
| 3988 views |
  • submit to reddit

There are many subjects one has to know when working with Swing and one of them is window closing. A beginner passes 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.

 

From http://blog.frankel.ch/properly-closing-swing-windows

Published at DZone with permission of Nicolas Frankel, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: