Java Reference
In-Depth Information
Example 10•6: BoxLayoutPane.java (continued)
Box buttonbox = Box.createHorizontalBox();
buttonbox.add(Box.createHorizontalGlue()); // stretchy space
buttonbox.add(new JButton("Okay"));
buttonbox.add(Box.createHorizontalGlue()); // stretchy space
buttonbox.add(new JButton("Cancel"));
buttonbox.add(Box.createHorizontalGlue()); // stretchy space
buttonbox.add(new JButton("Help"));
buttonbox.add(Box.createHorizontalGlue()); // stretchy space
this.add(buttonbox, BorderLayout.SOUTH);
// Create a component to display in the center of the panel
JTextArea textarea = new JTextArea();
textarea.setText("This component has 12-pixel margins on left and top"+
" and has 72-pixel margins on right and bottom.");
textarea.setLineWrap(true);
textarea.setWrapStyleWord(true);
// Use Box objects to give the JTextArea an unusual spacing
// First, create a column with 3 kids. The first and last kids
// are rigid spaces. The middle kid is the text area
Box fixedcol = Box.createVerticalBox();
fixedcol.add(Box.createVerticalStrut(12)); // 12 rigid pixels
fixedcol.add(textarea); // Component fills in the rest
fixedcol.add(Box.createVerticalStrut(72)); // 72 rigid pixels
// Now create a row. Give it rigid spaces on the left and right,
// and put the column from above in the middle.
Box fixedrow = Box.createHorizontalBox();
fixedrow.add(Box.createHorizontalStrut(12));
fixedrow.add(fixedcol);
fixedrow.add(Box.createHorizontalStrut(72));
// Now add the JTextArea in the column in the row to the panel
this.add(fixedrow, BorderLayout.CENTER);
}
}
GridBagLayout
GridBagLayout
is the most flexible and powerful of the AWT layout managers but
is also the most complicated, and sometimes the most frustrating. It arranges com-
ponents according to a number of constraints, which are stored in a
GridBagCon-
straints
object. In Java 1.1 and later, you pass a
GridBagConstraints
object as
the second argument to the
add()
method, along with the component to be
added. With Java 1.0, however, you must specify the constraints object for a com-
ponent by calling the
setConstraints()
method of the
GridBagLayout
itself.
The basic
GridBagLayout
layout policy is to arrange components at specified posi-
tions in a grid. The grid may be of arbitrary size, and the rows and columns of the
grid may be of arbitrary heights and widths. A component laid out in this grid may
occupy more than one row or column. The
gridx
and
gridy
fields of
GridBagCon-
straints
specify the position of the component in the grid, and the
gridwidth
and
gridheight
fields specify the number of columns and rows, respectively, that
the component occupies in the grid. The
insets
field specifies the margins that
should be left around each individual component, while
fill
specifies whether