Java Reference
In-Depth Information
Now the second button occupies one third of the space in the x direction — that corresponds to 5/(5 + 10)
of the total space in x that is available — 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.
The second button is also within the space allocated — 10 pixels at the top and bottom, 30 pixels on the
left, and 20 on the right (set by the insets constraint). You can see that for a given window size here, the
size of a grid position depends on the number of objects. The more components there are, the less space
each is allocated.
Suppose you wanted to add a third button, the same width as the Press button, and immediately below it.
You could do that by adding the following code immediately after that for the second button:
// Set constraints and add third button
constraints.insets = new java.awt.Insets(0,0,0,0); // No insets
constraints.gridx = 0; // Begin new row
constraints.gridwidth = 1; // Width as
"Press"
addButton("Push", constraints, gridbag, aWindow); // Add button to
content pane
TryGridBagLayout3.java
You reset the gridx constraint to zero to put the button at the start of the next row. It has a default grid-
width of one cell, like the others. The window would now look like the one shown in Figure 17-30 .
FIGURE 17-30
 
 
Search WWH ::




Custom Search