- Scenario:
You need to display a component in as much space as it can get.
-
If it is the only component in its container,
use
GridLayout or
BorderLayout.
Otherwise,
BorderLayout or
GridBagLayout
might be a good match.
If you use BorderLayout,
you will need to put the space-hungry component in the center.
With GridBagLayout,
you will need to set the constraints for the component so that
fill=GridBagConstraints.BOTH.
Another possibility is to use
BoxLayout,
making the space-hungry component
specify very large preferred and maximum sizes.
- Scenario:
You need to display a few components in a compact row
at their natural size.
-
Consider using a
JPanel to group the components
and using either the JPanel's default
FlowLayout manager
or the
BoxLayout manager.
SpringLayout
is also good for this.
- Scenario:
You need to display a few components of the same size
in rows and columns.
-
GridLayout is perfect for this.
- Scenario:
You need to display a few components in a row or column,
possibly with varying amounts of space between them,
custom alignment, or custom component sizes.
-
BoxLayout
is perfect for this.
- Scenario:
You need to display aligned columns,
as in a form-like interface
where a column of labels
is used to describe text fields in an adjacent column.
-
SpringLayout
is a natural choice for this.
The SpringUtilities class
used by several Tutorial examples
defines a makeCompactGrid method
that lets you easily align multiple rows and columns of components.
- Scenario:
You have a complex layout with many components.
-
Consider either using
a very flexible layout manager such as
GridBagLayout or
SpringLayout,
or grouping the components into one or more JPanels
to simplify layout.
If you take the latter approach,
each JPanel might use a different layout manager.
|