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.
does a better job
than we can do
Get the class of
Fig. 17.9 from a
footnote on les-
son page 17-3.
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.
Three JFrames with Box es in them