Java Reference
In-Depth Information
So far, our frame uses a
BorderLayout
, where the
WEST
area is empty. We can use this
area to add our toolbar buttons. There is one small problem, though. The
WEST
area of a
BorderLayout
can hold only one component, but we have two buttons.
The solution is simple. We add a
JPanel
to the frame's
WEST
area (as we know, a
JPanel
is a container), and then stick the two buttons into the
JPanel
. Code 11.14 shows the code to
do this.
Code 11.14
Adding a toolbar panel
with two buttons
// Create the toolbar with the buttons
JPanel toolbar =
new
JPanel();
smallerButton =
new
JButton(
"Smaller"
);
toolbar.add(smallerButton);
largerButton =
new
JButton(
"Larger"
);
toolbar.add(largerButton);
contentPane.add(toolbar, BorderLayout.WEST);
Exercise 11.45
Add two buttons labeled
Larger
and
Smaller
to your latest version of the
project, using code similar to the one above. Test it. What do you observe?
When we try this out, we see that it works partially but does not look as expected. The reason
is that a
JPanel
uses, by default, a
FlowLayout
, and a
FlowLayout
arranges its components
horizontally. We would like them arranged vertically.
We can achieve this by using another layout manager. A
GridLayout
does what we want. When
creating a
GridLayout
, constructor parameters determine how many rows and columns we
wish to have. A value of zero has a special meaning here, standing for “as many as necessary.”
Thus, we can create a single column
GridLayout
by using 0 as the number of rows and 1 as
the number of columns. We can then use this
GridLayout
for our
JPanel
by using the panel's
setLayout
method immediately after creating it:
JPanel toolbar = new JPanel();
toolbar.setLayout(new GridLayout(0, 1));
Alternatively, the layout manager can also be specified as a constructor parameter of the
container:
JPanel toolbar = new JPanel(new GridLayout(0, 1));
Exercise 11.46
Change your code so that your toolbar panel uses a
GridLayout
, as
discussed above. Test. What do you observe?
Search WWH ::
Custom Search