Java Reference
In-Depth Information
As can be seen in Figure 8-33, the components are no longer forced to the same height
and width as the highest and widest components. The first row's height has no relationship to
the second row's height, and the first column's width has no relationship to the second col-
umn's width.
The basic concept when using GridBagLayout is to configure the constraints to be used
for the component, notify the GridBagLayout manager of these constraints, and then add the
component to the pane. This is best exemplified in the following code snippet from Listing 8-26:
constraints.anchor = GridBagConstraints.WEST;
JButton one = new JButton("One");
grid.setConstraints(one, constraints);
theFrame.add(one);
Prior to this code snippet, the constraints were set to default values (starting in row 1,
column 1, centered in the grid, occupying one grid position, etc.). The first line changes the
location of each component so that they will now be left-justified. We then created our com-
ponent and notified the GridBagLayout that the specified constraints were to be used with
that particular component. Finally, we added the component to the panel.
â– 
Note Only one set of constraints is used throughout the application—when the setConstraints
method is called, the layout manager clones the constraints provided. This makes it easier for developing,
as you can set common constraint configuration at the start of your layout code and use those constraints
throughout the program.
Since components can span multiple rows and multiple columns, the GridBagLayout can-
not determine whether or not a component is the last component. Therefore, before adding
the last item to row 1, we must specify via the constraints that this will be the last component
in the row. The following line does this:
constraints.gridwidth = GridBagConstraints.REMAINDER;
As noted, we use the same set of constraints for all components. We set the constraints
to specify that the component will be the last component in the row, and then used that
constraint when adding the component to the container. However, if we do not reset the con-
straint, all future components will also appear as the last component in the row. The following
line does this:
constraints.gridwidth = 1;
To close this section, we will demonstrate how to specify that components span multiple
rows or columns. The program to do this is shown in Listing 8-27, and the output is shown in
Figure 8-34.
Search WWH ::




Custom Search