Java Reference
In-Depth Information
The
dispose
Method
The method
dispose
is a method in the class
JFrame
that releases any resources
used by the
JFrame
or any of its components. So, a call to
dispose
eliminates the
JFrame
and its components, but if the program has items that are not compo-
nents of the
JFrame
, then the program does not end. For example, in Display
18.2 the smaller window of the class
ConfirmWindow
invokes
dispose
(if the user
clicks the
"No"
button). That causes that smaller window to go away, but the
larger window remains.
dispose
The
dispose
Method
The class
JFrame
has a method named
dispose
that will eliminate the invoking
JFrame
without ending the program. When
dispose
is invoked, the resources consumed by the
JFrame
and its components are returned for reuse, so the
JFrame
is gone, but the program
does not end (unless
dispose
eliminates all elements in the program, as in a one-window
program). The method
dispose
is often used in a program with multiple windows to elimi-
nate one window without ending the program.
SYNTAX
JFrame_Object
.dispose();
The
JFrame_Object
is often an implicit
this
. A complete example of using
dispose
can be
seen in Display 18.2.
PITFALL: Forgetting to Invoke
setDefaultCloseOperation
If you register a window listener to respond to window events from a
JFrame
, you
should also include an invocation of the method
setDefaultCloseOperation
, typi-
cally in the
JFrame
constructor. This is because the default or other behavior set by
setDefaultCloseOperation
takes place even if there is a window listener. If you do
not want any actions other than those provided by the window listener(s), you
should include the following in the
JFrame
constructor:
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
If you do not include any invocation of
setDefaultCloseOperation
, the default
action is the same as if you had included the following invocation
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
which hides the
JFrame
when the close-window button is clicked. (The actions of
any registered window listener are also performed.)
■