Java Reference
In-Depth Information
EXAMPLE:
A Simple Window
Display 17.2 contains a Swing program that produces a simple window. The win-
dow contains nothing but a button on which is written
If
the user follows the instructions and clicks the button with his or her mouse, the
program ends.
The
"Click to end program."
statements give the names of the classes used and which package they
are in. What we and others call the
import
Swing library
is the package named
.
javax.swing
The
AWT library
is the package
. Note that one package name contains an “
”
java.awt
x
and one does not.
This program is a simple class definition with only a
method. The first line
main
in the
method creates an object of the class
. That line is reproduced
main
JFrame
below:
JFrame firstWindow =
new
JFrame();
This is an ordinary declaration of a variable named
and an invocation
firstWindow
of the no-argument constructor for the class
. A
object is a basic win-
JFrame
JFrame
dow. A
object includes a border and the usual three buttons for minimizing the
window down to an icon, changing the size of the window, and closing the window.
These buttons are shown in the upper-right corner of the window, which is typical,
but if your operating system normally places these buttons someplace else, that is
where they will likely be located in a
JFrame
on your computer.
JFrame
The initial size of the
window is set using the
method
, as
JFrame
JFrame
setSize
follows:
firstWindow.setSize(WIDTH, HEIGHT);
constants. The units of measure are
pixels, so the window produced is 300 pixels by 200 pixels. (The term
In this case
and
are defined
WIDTH
HEIGHT
int
is defined
in the box entitled “Pixel.”) As with other windows, you can change the size of a
pixel
window.
The buttons for minimizing the window down to an icon and for changing the size
of the window behave as they do in any of the other windows you have used. The min-
imization button shrinks the window down to an icon. (To restore the window, you
click the icon.) The second button changes the size of the window back and forth from
full screen to a smaller size. The close-window button can behave in different ways
depending on how it is set by your program.
The behavior of the close-window button is set with the
by using your mouse to drag a corner of the
JFrame
JFrame
method
JFrame
setDefault-
. The line of the program that sets the behavior of the close-window but-
ton is reproduced below:
CloseOperation
firstWindow.setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE);
(continued)