Java Reference
In-Depth Information
17.3.1
JPanels and FlowLayout managers
A
JPanel
is a transparent Swing container used to group related components. As
an example, consider the
JFrame
in Fig. 17.9. It has a
JPanel
in the center and
JLabels
in the north and south. The
JPanel
contains four buttons.
Figure 17.9 is an instance of class
PanelDemo
of Fig. 17.10. The class has a
field
p
, which is initialized to contain a
JPanel
. In the constructor, four buttons
are added to
p
, one by one, using procedure
p.add
. Unlike previous calls of pro-
cedure
add
, these calls have only one argument; we explain why later.
Next, the content pane of the
JFrame
is stored in variable
cp
, and the
JPanel
and labels are added to the content pane. Finally, the
JFrame
is packed.
Activity 17-3.1
does a better job
than we can do
on paper.
Get the class of
Fig. 17.9 from a
footnote on les-
son page 17-3.
FlowLayout managers
Much like a
JFrame
's content pane, a
JPanel
is a subclass of
Container
, so
a
JPanel
can contain other components —four buttons in this case.
By default, a
JPanel
uses as layout manager an instance of class
FlowLay-
out
, not
BorderLayout
. When using a
FlowLayout
manager, components are
added using a one-argument method
add
. Any number of components can be
added, and they appear from left to right, in the order added.
If there is not enough room to hold components in a
JPanel
horizontally,
new rows are added to contain them. Thus, you can see why the layout manager
is called a
flow layout
manager; the components in it go with the flow.
That is all there is to
FlowLayout
managers.
Activity 17-3.1
demos adding
new rows.
Figure 17.11:
Three
JFrames
with
Box
es in them
Search WWH ::
Custom Search