Java Reference
In-Depth Information
A GridBagConstraints object has a number of fields to store the layout param-
eters of a component. The class does not have any set or get methods to access
these parameters. Instead the fields are public and can be directly accessed from
the outside - quite a non-object-oriented approach. In the following we list some
of the fields and their interpretation.
the number of columns spanned
int
gridwidth
gridheight the number of rows spanned
int
the left-most column
int
gridx
the top-most row
int
gridy
the horizontal weight
double weightx
the vertical weight
double weighty
determines whether the component is
resized to fit the bag.
int
fill
The layout parameter fill determines whether an embedded component should
be resized such that it fills the bag. The possible values NONE , BOTH , HORIZONTAL
and VERTICAL are defined as constants in GridBagConstraints .Wealways use
fill = BOTH here, which resizes the component to precisely fit its bag. The reader
is encouraged to try other settings for the various components. Class GridBag-
Constraints has more fields which we do not discuss here; the user is referred
to the Java documentation.
The following code snippet shows how to set the constraints for panel A of
our application. First an instance of GridBagConstraints is generated, then the
fields are set to the desired values. The values are those of the corresponding line
in Table 17.2.
GridBagConstraints constraintsA = new GridBagConstraints();
constraintsA.gridwidth = 1;
// The width of panel A.
constraintsA.gridheight = 2;
// The height of panel A.
constraintsA.gridx
= 0;
// Left column of panel A.
constraintsA.gridy
= 0;
// Top row of panel A.
constraintsA.weightx
= 2.0; // The horizontal weight of panel A.
constraintsA.weighty
= 1.0; // The vertical weight of panel A.
constraintsA.fill
= GridBagConstraints.BOTH; // resize panel A
// to fit its bag.
We still have to link the constraints to the panel. This is done by using method:
setConstraints(Component embeddedComp,GridBagConstraints constraints);
of class GridBagLayout .Inour case the panel is called panelA and the constraints
constraintsA :
setConstraints(panelA,constraintsA);
Search WWH ::




Custom Search