Java Reference
In-Depth Information
JFrame
. Class
ImageIcon
represents an image that can be displayed on a
JLabel
, and class
JFrame
represents the window that will contain all the labels.
Line 13 creates a
JLabel
that displays its constructor argument—the string
"North"
.
Line 16 declares local variable
labelIcon
and assigns it a new
ImageIcon
. The constructor
for
ImageIcon
receives a
String
that specifies the path to the image. Since we specify only
a filename, Java assumes that it's in the same directory as class
LabelDemo
.
ImageIcon
can
load images in GIF, JPEG and PNG image formats. Line 19 declares and initializes local
variable
centerLabel
with a
JLabel
that displays the
labelIcon
. Line 22 declares and ini-
tializes local variable
southLabel
with a
JLabel
similar to the one in line 19. However,
line 25 calls method
setText
to change the text the label displays. Method
setText
can
be called on any
JLabel
to change its text. This
JLabel
displays both the icon and the text.
Line 28 creates the
JFrame
that displays the
JLabel
s, and line 30 indicates that the pro-
gram should terminate when the
JFrame
is closed. We attach the labels to the
JFrame
in
lines 34-36 by calling an overloaded version of method
add
that takes two parameters. The
first parameter is the component we want to attach, and the second is the region in which
it should be placed. Each
JFrame
has an associated
layout
that helps the
JFrame
position
the GUI components that are attached to it. The default layout for a
JFrame
is known as a
BorderLayout
and has five regions—
NORTH
(top),
SOUTH
(bottom),
EAST
(right side),
WEST
(left side) and
CENTER
. Each of these is declared as a constant in class
BorderLayout
. When
calling method
add
with one argument, the
JFrame
places the component in the
CENTER
automatically. If a position already contains a component, then the new component takes
its place. Lines 38 and 39 set the size of the
JFrame
and make it visible on screen.
GUI and Graphics Case Study Exercise
9.1
Modify GUI and Graphics Case Study Exercise 8.1 to include a
JLabel
as a status bar that
displays counts representing the number of each shape displayed. Class
DrawPanel
should declare a
method that returns a
String
containing the status text. In
main
, first create the
DrawPanel
, then
create the
JLabel
with the status text as an argument to the
JLabel
's constructor. Attach the
JLabel
to the
SOUTH
region of the
JFrame
, as shown in Fig. 9.14.
Fig. 9.14
|
JLabel
displaying shape statistics.