Java Reference
In-Depth Information
Adding the toolbar itself couldn't be easier. A toolbar is a Swing component defined by the
JToolBar
class. You can add a member to the
SketchFrame
class for a toolbar by adding the following field to
the class definition:
private JToolBar toolBar = new JToolBar(); // Window toolbar
You can position this following the declaration of the
menuBar
member. It simply creates a
JToolBar
object as a member of the class. To add it to the frame window, you need to add the following statement
after the existing code in the
SketchFrame
constructor:
getContentPane().add(toolBar, BorderLayout.NORTH);
This adds the (empty) toolbar to the top of the content pane for the frame window. The content pane has the
BorderLayout
manager as the default, which is very convenient. A
JToolBar
object should be added to a
Container
using the
BorderLayout
manager since it is normally positioned at one of the four sides of a
component. An empty toolbar is not much use though, so let's see how to add buttons.
Adding Buttons to a Toolbar
The
JToolBar
class inherits the
add()
methods from the
Container
class, so you could create
JButton
objects and add them to the toolbar. However, since a toolbar almost always has buttons corresponding to
menu functions, a much better way is to use the
add()
method defined in the
JToolBar
class to add an
Action
object to the toolbar. We can use this to add any of the
Action
objects that we created for our
menus, and have the toolbar button events taken care of without any further work.
For example, we could add a button for the
openAction
object corresponding to the
Open
menu item
in the
File
menu with the statement:
toolBar.add(openAction); // Add a toolbar button
That's all you need basically. The
add()
method will create a
JButton
object based on the
Action
object passed as the argument. A reference to the
JButton
object is returned in case you want to store
it to manipulate it in some way - adding a border for instance. Let's see how that looks.
Try It Out - Adding a Toolbar Button
Assuming you have added the declaration for the
toolBar
object to the
SketchFrame
class, you just
need to add a couple of statements preceding the last statement in the constructor to add the toolbar to
the content pane:
public SketchFrame(String title) {
// Constructor code as before...
JButton button = toolBar.add(openAction); // Add toolbar button
button.setBorder(BorderFactory.createRaisedBevelBorder()); // Add button border
getContentPane().add(toolBar, BorderLayout.NORTH); // Add the toolbar
}