Java Reference
In-Depth Information
In Display 17.7, we added labels as follows:
JLabel label1 =
new
JLabel("First label");
add(label1, BorderLayout.NORTH);
JLabel label2 =
new
JLabel("Second label");
add(label2, BorderLayout.SOUTH);
JLabel label3 =
new
JLabel("Third label");
add(label3, BorderLayout.CENTER);
When you use a
BorderLayout
manager, you give the location of the component
added as a second argument to the method
add
, as in the following:
add(label1, BorderLayout.NORTH);
The labels (or other components to be added) need not be added in any particular
order, because the second argument completely specifies where the label is placed.
BorderLayout.NORTH
,
BorderLayout.SOUTH
,
BorderLayout.EAST
,
BorderLayout.
WEST
, and
BorderLayout.CENTER
are five string constants defined in the class
Border-
Layout
. The values of these constants are
"North"
,
"South"
,
"East"
,
"West"
, and
"Center"
. Although you can use a quoted string such as
"North"
as the second argu-
ment to
add
, it is more consistent with our general style rules to use a defined constant
like
BorderLayout.NORTH
.
You need not use all five regions. For example, in Display 17.7 we did not use the
regions
BorderLayout.EAST
and
BorderLayout.WEST
. If some regions are not used,
any extra space is given to the
BorderLayout.CENTER
region, which is the largest
region.
(The space is divided between regions as follows: Regions are allocated space in the
order first north and south, second east and west, and last center. So, in particular, if
there is nothing in the north region, then the east and west regions will extend to the
top of the space.)
From this discussion, it sounds as though you can place only one item in each
region, but later in this chapter, when we discuss
panels,
you will see that there
is a way to group items so that more than one item can (in effect) be placed in
each region.
There are some standard layout managers defined for you in the
java.awt
package,
and you can also define your own layout managers. However, for most purposes, the
layout managers defined in the standard libraries are all that you need, and we will not
discuss how you can create your own layout manager classes.
Flow Layout Managers
The
FlowLayout
manager
is the simplest layout manager. It arranges components
one after the other, going from left to right, in the order in which you add them to
the
JFrame
(or other container class) using the method
add
. For example, if the class