Java Reference
In-Depth Information
The second button is also within the space allocated - ten pixels at the top and bottom, thirty pixels on
the left and twenty on the right (set with 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 they will each be allocated.
Suppose we wanted to add a third button, the same width as the Press button, and immediately below
it. We could do that by adding the following code immediately after that for the second button:
// Set constraints and add third button
constraints.insets = new Insets(0,0,0,0); // No insets
constraints.gridx = 0; // Begin new row
constraints.gridwidth = 1; // Width as "Press"
addButton("Push", constraints, gridbag); // Add button to content pane
We reset the gridx constraint to zero to put the button at the start of the next row. It has a default
gridwidth of 1 cell, like the others. The window would now look like:
Having seen how it looks now, clearly it would be better if the GO button were the height of Press and
Push combined. To arrange them like this, we need to make the height of the GO button twice that of
the other two buttons. The height of the Press button is 1 by default, so by making the height of the GO
button 2, and resetting the gridheight constraint of the Push button to 1 , we should get the desired
result. Modify the code for the second and third buttons to:
// Set constraints and add second button
constraints.weightx = 5.0; // Weight half of first
constraints.gridwidth = constraints.REMAINDER; // Rest of the row
constraints.insets = new Insets(10, 30, 10, 20); // Left 30 & right 20
constraints.gridheight = 2; // Height 2x "Press"
addButton("GO", constraints, gridbag); // Add button to content pane
// Set constraints and add third button
constraints.gridx = 0; // Begin new row
constraints.gridwidth = 1; // Width as "Press"
constraints.gridheight = 1; // Height as "Press"
constraints.insets = new Insets(0, 0, 0, 0); // No insets
addButton("Push", constraints, gridbag); // Add button to content pane
Search WWH ::




Custom Search