Java Reference
In-Depth Information
Table 14-1. Layout managers
Name
Notes
Default on
Flows across the container
(J)Panel
,
(J)Applet
FlowLayout
Five “geographic” regions
(J)Frame
,
(J)Window
BorderLayout
Regular grid (all items same size)
None
GridLayout
Display one of many components at a time; useful for wizard-style
layouts
None
CardLayout
Very flexible but maximally complex
None
GridBagLayout
Single row or column of components
None
BoxLayout
(Swing)
Because we've broached the subject of layout management, I should mention that each com-
ponent has a method called
getPreferredSize()
, which the layout managers use in decid-
ing how and where to place components. A well-behaved component overrides this method
to return something meaningful. A button or label, for example, will indicate that it wishes to
be large enough to contain its text and/or icon, plus a bit of space for padding. And, if your
JFrame
is full of well-behaved components, you can set its size to be “just the size of all in-
cluded components, plus a bit for padding,” just by calling the
pack()
method, which takes
no arguments. The
pack()
method goes around and asks each embedded component for its
preferred size (and any nested container's
getPreferredSize()
will ask each of its com-
ponents, and so on). The
JFrame
is then set to the best size to give the components their pre-
ferred sizes as much as is possible. If not using
pack()
, you need to call the
setSize()
method, which requires either a width and a height, or a
Dimension
object containing this in-
formation.
A
FlowLayout
is the default in
JPanel
and
Applet/JApplet
. It simply lays the components
out along the “normal” axis (left to right in European and English-speaking locales, right to
left in Hebrew or Arabic locales, and so on, as set by the user's
Locale
settings). The overall
collection of them is centered within the window.