Java Reference
In-Depth Information
new
new
ButtonDemo2L
().
setVisible
(
true
true
);
}
}
Terminating a Program with “Window Close”
Problem
Nothing happens when you click 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
Use
JFrame
's
setDefaultCloseOperation()
method or add a
WindowListener
and 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 because 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. You can listen for
Win-
dowEvents
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 key-
board and mouse events) or deactivated. Or you can find out when the window is iconified or
deiconified: 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 noti-
fied when the user requests that the window be closed. (Some sample close buttons are
“default close operation.” Alternatively, with any
Window
subclass, you can provide a
Win-
dowListener
to be notified of window events.