Java Reference
In-Depth Information
izontally to the sides of the container and are as tall as the components placed in those
regions. The
EAST
and
WEST
regions expand vertically between the
NORTH
and
SOUTH
regions and are as wide as the components placed in those regions. The component placed
in the
CENTER
region
expands to fill all remaining space in the layout
(which is the reason the
JTextArea
in Fig. 12.37 occupies the entire window). If all five regions are occupied, the
entire container's space is covered by GUI components. If the
NORTH
or
SOUTH
region is not
occupied, the GUI components in the
EAST
,
CENTER
and
WEST
regions expand vertically to
fill the remaining space. If the
EAST
or
WEST
region is not occupied, the GUI component
in the
CENTER
region
expands horizontally to fill the remaining space
. If the
CENTER
region is
not
occupied, the area is left
empty
—the other GUI components do
not
expand to fill the
remaining space. The application of Figs. 12.41-12.42 demonstrates the
BorderLayout
layout manager by using five
JButton
s.
1
// Fig. 12.41: BorderLayoutFrame.java
2
// BorderLayout containing five buttons.
3
import
java.awt.BorderLayout;
4
import
java.awt.event.ActionListener;
5
import
java.awt.event.ActionEvent;
6
import
javax.swing.JFrame;
7
import
javax.swing.JButton;
8
9
public
class
BorderLayoutFrame
extends
JFrame
implements
ActionListener
10
{
11
private final
JButton[] buttons;
// array of buttons to hide portions
12
private
static final
String[] names = {
"Hide North"
,
"Hide South"
,
13
"Hide East"
,
"Hide West"
,
"Hide Center"
};
14
private final
BorderLayout layout;
15
16
// set up GUI and event handling
17
public
BorderLayoutFrame()
18
{
19
super
(
"BorderLayout Demo"
);
20
21
layout =
new
BorderLayout(
5
,
5
);
// 5 pixel gaps
22
setLayout(layout);
23
buttons =
new
JButton[names.length];
24
25
// create JButtons and register listeners for them
26
for
(
int
count =
0
; count < names.length; count++)
27
{
28
buttons[count] =
new
JButton(names[count]);
29
buttons[count].addActionListener(
this
);
30
}
31
32
add(buttons[
0
],
BorderLayout.NORTH
);
33
add(buttons[
1
],
BorderLayout.SOUTH
);
34
add(buttons[
2
],
BorderLayout.EAST
);
35
add(buttons[
3
],
BorderLayout.WEST)
;
36
add(buttons[
4
],
BorderLayout.CENTER
);
37
}
Fig. 12.41
|
BorderLayout
containing five buttons. (Part 1 of 2.)