Java Reference
In-Depth Information
How It Works
Because the process will be the same for every button added, we have implemented the helper function
addButton()
. This creates a
Button
object, associates the
GridBagConstraints
object with it in
the
GridBagLayout
object, and then adds it to the content pane of the frame window.
After creating the layout manager and
GridBagConstraints
objects we set the values for
weightx
and
weighty
to 10.0. A value of 1.0 would have the same effect. We set the
fill
constraint to
BOTH
to make the component fill the space it occupies. Note that when the
setConstraints()
method is
called to associate the
GridBagConstraints
object with the button object, a copy of the constraints
object is stored in the layout - not the object we created. This allows us to change the constraints object
and use it for the second button without affecting the constraints for the first.
The buttons are more or less equal in size in the
x
direction (they would be exactly the same size if the
labels were the same length) because the
weightx
and
weighty
values are the same for both. Both
buttons fill the space available to them because the
fill
constraint is set to
BOTH
. If
fill
was set to
HORIZONTAL
, for example, the buttons would be the full width of the grid positions they occupy, but
just high enough to accommodate the label, since they would have no preferred size in the
y
direction.
If we alter the constraints for the second button to:
// Set constraints and add second button
constraints.weightx = 5.0; // Weight half of first
constraints.insets = new Insets(10, 30, 10, 20); // Left 30 & right 20
constraints.gridwidth = constraints.RELATIVE; // Rest of the row
addButton("GO", constraints, gridbag); // Add button to content pane
the application window will be as
shown:
Now the second button occupies one third of the space in the
x
direction - that is a proportion of
5/(5+10) of the total - and the first button occupies two thirds. Note that the buttons still occupy one
grid cell each - the default values for
gridwidth
and
gridheight
of 1 apply - but the
weightx
constraint values have altered the relative sizes of the cells for the two buttons in the
x
direction.