Java Reference
In-Depth Information
Summarizing, the following steps are necessary to use a grid-bag layout for
embedding components
comp0
,...
compK
,...
compN
into parent component
parent
:
Sketch the desired layout on paper and determine how many rows and columns
are necessary. Also determine the weights you want to use.
■
Create an instance
gbl
of
GridBagLayout
and assign it to
parent
by
par-
ent.setLayout(gbl)
.
■
For every component
compK
to be embedded do the following:
(a) Create an instance
constraintsK
of
GridBagConstraints
and set the pa-
rameters.
(b) Link the constraints
constraintsK
to
compK
using
gbl.setConstraints-
(compK,constraintsK).
(c) Embed
compK
into
parent
by
parent.add(compK)
(or
parent
.getContentPane().add(compK)
in case
parent
is a frame).
■
Creating and setting the constraints for every component would result in many
lines of nearly identical code. In the example application
GridBagFrame
we de-
fined a private method
easyConstraints
that does all this work. It receives the
constraint values, the component and the layout as arguments. It then creates an
instance of
GridBagConstraints
, sets the values, and links constraints and com-
ponents. The field
fill
is always set to
BOTH
. The GUI created by this program is
shown in Figure 17.4.
Figure 17.4 The result of application
GridBagFrame
Search WWH ::
Custom Search