Java Reference
In-Depth Information
If we try this out, we can see that we are getting closer, but we still do not have what we
want. Our buttons now are much larger than we intended. The reason is that a container in a
BorderLayout
(our toolbar
JPanel
in this case) always covers its whole area (the
WEST
area
in our frame). And a
GridLayout
always resizes its components to fill the whole container.
A
FlowLayout
does not do this; it is quite happy to leave some empty space around the
components. Our solution is therefore to use both: the
GridLayout
to arrange the buttons in
a column and a
FlowLayout
around it to allow some space. We end up with a
GridLayout
panel inside a
FlowLayout
panel inside a
BorderLayout
. Code 11.15 shows this solution.
Constructions like this are very common. You will often nest various containers inside other
containers to create exactly the look you want.
Code 11.15
Using a nested
GridLayout
container
inside a
FlowLayout
container
// Create the toolbar with the buttons.
JPanel toolbar =
new
JPanel();
toolbar.setLayout(
new
GridLayout(0, 1));
smallerButton =
new
JButton(
"Smaller"
);
toolbar.add(smallerButton);
largerButton =
new
JButton(
"Larger"
);
toolbar.add(largerButton);
// Add toolbar into panel with flow layout for spacing.
JPanel flow =
new
JPanel();
flow.add(toolbar);
contentPane.add(flow, BorderLayout.WEST);
Our buttons now look quite close to what we were aiming for. Before adding the finishing
polish, we can first work on making the buttons work.
We need to add two methods, named, for instance,
makeLarger
and
makeSmaller
, to do the
actual work, and we need to add action listeners to the buttons that invoke these methods.
Exercise 11.47
In your project, add two method stubs named
makeLarger
and
make
Smaller
. Initially, put just a single
println
statement into these method bodies to see when
they have been called. The methods can be private.
Exercise 11.48
Add action listeners to the two buttons that invoke the two new methods.
Adding action listeners to buttons is identical to adding action listeners to menu items. You
can essentially copy the code pattern from there. Test it. Make sure your
makeSmaller
and
makeLarger
methods get called by activating the buttons.
Search WWH ::
Custom Search