Java Reference
In-Depth Information
constraints.anchor = GridBagConstraints.EAST;
gridbag.setConstraints(toLabel, constraints);
add(toLabel);
// add the text field
JTextField to = new JTextField();
constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 9;
constraints.gridheight = 1;
constraints.weightx = 90;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(to, constraints);
add(to);
}
The label and text fields each use their own constraints object (reusing the
constraints
variable). Their
gridx
and
gridy
values put the label at position (0,0) and the text field
at position (0,1). The
gridwidth
values make the label one cell wide and the text field
nine cells wide.
They use the
fill
value differently: The label has
NONE
, so it does not expand in either
direction, and the text field has
HORIZONTAL
, so it expands horizontally only. (The other
possible values are
VERTICAL
or
BOTH
.)
11
They also use
anchor
differently. The label is aligned along the right edge of the cell
through the
EAST
class variable. The text field aligns to the left edge through
WEST
.
Each of the compass directions and
CENTER
can be used:
NORTH
,
NORTHEAST
,
EAST
,
SOUTHEAST
,
SOUTH
,
SOUTHWEST
,
WEST
, and
NORTHWEST
.
The most complex aspect of grid bag constraints are the
weightx
and
weighty
values.
These variables hold arbitrary integer (or double) values that indicate how big compo-
nents should be in relation to each other.
The To label has a
weightx
of 10, and the adjacent text field has a
weightx
of 90, using
the same scale as the sketch in Figure 11.5. These values make the text field nine times
as large as the label. The values are arbitrary: If the label were 3 and the text field were
27, the field would still be nine times as large.
When you don't need to give components different weights, use the same value through-
out a row or column. For instance, the To label and field both have
weighty
values of
100
, so they have the same height as any other components below them in the same
column.