Java Reference
In-Depth Information
38
39
// handle button events
40
@Override
41
public
void
actionPerformed(ActionEvent event)
42
{
43
// check event source and lay out content pane correspondingly
44
for
(
JButton
button : buttons)
45
{
46
if
(event.getSource() == button)
47
button.setVisible(
false
);
// hide the button that was clicked
48
else
49
button.setVisible(
true
);
// show other buttons
50
}
51
52
layout.layoutContainer(getContentPane());
// lay out content pane
53
}
54
}
// end class BorderLayoutFrame
Fig. 12.41
|
BorderLayout
containing five buttons. (Part 2 of 2.)
Line 21 of Fig. 12.41 creates a
BorderLayout
. The constructor arguments specify the
number of pixels between components that are arranged horizontally (
horizontal gap
space
) and between components that are arranged vertically (
vertical gap space
), respec-
tively. The default
is
one pixel of gap space horizontally and vertically. Line 22 uses
method
setLayout
to set the content pane's layout to
layout
.
We add
Component
s to a
BorderLayout
with another version of
Container
method
add
that takes two arguments—the
Component
to add and the region in which the
Compo-
nent
should appear. For example, line 32 specifies that
buttons[0]
should appear in the
NORTH
region. The components can be added in
any
order, but only
one
component should
be added to each region.
Look-and-Feel Observation 12.18
If no region is specified when adding a
Component
to a
BorderLayout
, the layout manager
assumes that the
Component
should be added to region
BorderLayout.CENTER
.
Common Programming Error 12.5
When more than one component is added to a region in a
BorderLayout
, only the last
component added to that region will be displayed. There's no error that indicates this
problem.
Class
BorderLayoutFrame
implements
ActionListener
directly in this example, so the
BorderLayoutFrame
will handle the events of the
JButton
s. For this reason, line 29 passes
the
this
reference to the
addActionListener
method of each
JButton
. When the user clicks
a particular
JButton
in the layout, method
actionPerformed
(lines 40-53) executes. The
enhanced
for
statement at lines 44-50 uses an
if
…
else
to hide the particular
JButton
that
generated the event. Method
setVisible
(inherited into
JButton
from class
Component
) is
called with a
false
argument (line 47) to hide the
JButton
. If the current
JButton
in the
array is not the one that generated the event, method
setVisible
is called with a
true
argu-
ment (line 49) to ensure that the
JButton
is displayed on the screen. Line 52 uses
Layout-