Terminating a Program with “Window Close”

Problem

Nothing happens when you click on the close button on the title bar of an AWT Frame. When you do this on a Swing JFrame, the window disappears but the application does not exit.

Solution

Add a WindowListener ; have it exit the application.

Discussion

Main windows -- subclasses of java.awt.Window , such as (J)Frames and (J)Dialogs -- are treated specially. Unlike all other Component subclasses, Window and its subclasses are not initially visible. This is sensible, as they have to be packed or resized, and you don’t want the user to watch the components getting rearranged. Once you call a Window’s setVisible(true) method, all components inside it become visible. And you can listen for WindowEvents on a Window.

The WindowListener interface contains a plenitude of methods to notify a listener when anything happens to the window. You can be told when the window is activated (gets keyboard and mouse events) or deactivated. Or you can find out when the window is iconified or de-iconified: these are good times to suspend and resume processing, respectively. You can be notified the first time the window is opened. And, most importantly for us, you can be notified when the user requests that the window be closed. (Some sample close buttons are show in Figure 13-4.) The windowClosing method of your WindowListener is called when the user clicks on the close button (this depends on the window system and, on X Windows, on the window manager) or ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.