Java Reference
In-Depth Information
insets
—An
Insets
object that sets the whitespace around the component inside
its cell
n
ipadx
—The amount to expand the component's width beyond its minimum size
n
ipady
—The amount to expand the component's height
n
With the exception of
insets
, all these can hold integer values. The easiest way to use
this class is to create a constraints object with no arguments and set its variables individ-
ually. Variables not explicitly set use their default values.
The following code creates a grid bag layout and a constraints object used to place com-
ponents in the grid:
Container pane = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
pane.setLayout(gridbag);
The constraints object can be configured with a set of assignment statements:
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
This code sets up a constraint that can be used to put a component at grid position (0,0)
that is two cells wide and one cell tall.
The component's size within its cell and position are set with class variables of
GridBagConstraints
. The component will be centered in its cell (an
anchor
value of
CENTER
) and does not expand to fill the entire cell (a
fill
value of
NONE
).
The
weightx
and
weighty
values only make sense in relation to the same values for
other components, as described in detail later in this section.
A component is added to a grid bag layout in two steps:
1.
The layout manager's
setConstraints(
Component
,
GridBagConstraints
)
method is called with the component and constraints objects as arguments.
2.
The component is added to a container that uses that manager.