Java Reference
In-Depth Information
4
5
public class
ShowBorderLayout
extends
JFrame
{
6
public
ShowBorderLayout() {
7
// Set BorderLayout with horizontal gap 5 and vertical gap 10
8 setLayout(
new
BorderLayout(
5
,
10
)
);
set layout
9
10
// Add buttons to the frame
11 add(
new
JButton(
"East"
), BorderLayout.EAST);
12 add(
new
JButton(
"South"
), BorderLayout.SOUTH);
13 add(
new
JButton(
"West"
), BorderLayout.WEST);
14 add(
new
JButton(
"North"
), BorderLayout.NORTH);
15 add(
new
JButton(
"Center"
), BorderLayout.CENTER);
16 }
17
18
/** Main method */
19
public static void
main(String[] args) {
20 ShowBorderLayout frame =
new
ShowBorderLayout();
21 frame.setTitle(
"ShowBorderLayout"
);
22 frame.setSize(
300
,
200
);
23 frame.setLocationRelativeTo(
null
);
// Center the frame
24 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
25 frame.setVisible(
true
);
26 }
27 }
The buttons are added to the frame (lines 11-15). Note that the
add
method for
BorderLayout
is different from the one for
FlowLayout
and
GridLayout
. With
BorderLayout
, you spec-
ify where to put the components.
It is unnecessary to place components to occupy all the areas. If you remove the East but-
ton from the program and rerun it, you will see that the Center button stretches rightward to
occupy the East area.
add buttons
create the frame
set visible
Note
BorderLayout
interprets the absence of an index specification as
BorderLayout.CENTER
. For example,
add(component)
is the same as
add(Component, BorderLayout.CENTER)
. If you add two components to a
container of
BorderLayout
, as follows,
container.add(component1);
container.add(component2);
only the last component is displayed.
12.5.4 Properties of Layout Managers
Layout managers have properties that can be changed dynamically.
■
FlowLayout
has
alignment
,
hgap
, and
vgap
properties. You can use the
setAlignment
,
setHgap
, and
setVgap
methods to specify the alignment and
the horizontal and vertical gaps.
■
GridLayout
has the
rows
,
columns
,
hgap
, and
vgap
properties. You can use
the
setRows
,
setColumns
,
setHgap
, and
setVgap
methods to specify the
number of rows, the number of columns, and the horizontal and vertical gaps.
■
BorderLayout
has the
hgap
and
vgap
properties. You can use the
setHgap
and
setVgap
methods to specify the horizontal and vertical gaps.
In the preceding sections an anonymous layout manager is used because the properties of a
layout manager do not change once it is created. If you have to change the properties of a lay-
out manager dynamically, the layout manager must be explicitly referenced by a variable. You