Java Reference
In-Depth Information
How It Works
Because the process is the same for every button that you add, you have implemented a helper method,
addButton() . This method 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, you set the values for weightx and
weighty to 10.0. A value of 1.0 or 100.0 would have the same effect because it is the relative values
that these variables have for the constraints on components in a column or row, not their absolute values.
You set the fill constraint to BOTH to make the component fill the space it occupies. When setCon-
straints() is called to associate the GridBagConstraints object with the button object, it creates a
copy of the constraints object that you pass as the argument, and a reference to the copy is stored in
the layout — not a reference to the object that you created. This enables you to change the constraints
object that you created 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 la-
bels 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 because they would have no preferred size in the y direction.
If you 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 java.awt.Insets(10, 30, 10, 20); // Left 30
& right 20
constraints.gridwidth = GridBagConstraints.RELATIVE;
// Rest of
the row
addButton("GO", constraints, gridbag); // Add button to
content pane
TryGridBagLayout2.java
the application window is as shown in Figure 17-29 .
FIGURE 17-29
 
 
Search WWH ::




Custom Search