Java Reference
In-Depth Information
Vertical versus horizontal layout
Because the argument to the
Box
constructor is
BoxLayout.X-AXIS
, the line
of components is horizontal. If we change the argument to
BoxLayout.Y_AXIS
,
the line of components is vertical, as shown in the center of Fig. 17.11.
A rectangular layout of buttons
Class
Box
and layout manager
BoxLayout
, together with the fact that we can
nest components, can be used to construct quite complex layouts. As an example
of this, we show code that, when placed in the constructor, produces the right-
most
JFrame
of Fig. 17.11, which looks like a rectangle of buttons.
First, create variable
leftBox
, store in it a vertical
Box
, and add three but-
tons to it:
Box leftBox=
new
Box(BoxLayout.Y_AXIS);
leftBox.add(
new
JButton(" 00 "));
leftBox.add(
new
JButton(" 01 "));
leftBox.add(
new
JButton(" 02 "));
Second, create a
rightBox
, store in it a vertical
Box
, and add three buttons
to it:
Box rightBox=
new
Box(BoxLayout.Y_AXIS);
rightBox.add(
new
JButton(" 10 "));
rightBox.add(
new
JButton(" 11 "));
rightBox.add(
new
JButton(" 12 "));
Third, create variable
b
, store in it a horizontal
Box
, and add boxes
leftBox
and
rightBox
to it:
Box b=
new
Box(BoxLayout.X_AXIS);
b.add(leftBox);
b.add(rightBox);
Finally, add the labels and box
b
to the content pane and pack it:
Container cp= getContentPane();
cp.add(
new
JLabel(" north "), BorderLayout.NORTH);
cp.add(
new
JLabel(" south "), BorderLayout.SOUTH);
cp.add(b, BorderLayout.CENTER);
pack();
The ability to nest containers in other containers, together with the ability to
create horizontally or vertically placed components, makes it quite easy to con-
struct complex GUI designs.
Leaving spaces in a Box
Look at the
JFrame
on the right in Fig. 17.11. Suppose we do not want the
right middle button, but we do want the lower right button to remain at the bot-
Search WWH ::
Custom Search