Java Reference
In-Depth Information
The four buttons in the first group are for the most frequently used functions in the File menu. The other
two groups of four buttons select the element type and element color, respectively. So how are you going to
put this toolbar together?
Adding the toolbar itself couldn't be easier. A toolbar is a Swing component defined by the
javax.swing.JToolBar class. You can add a member to the SketcherFrame 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 ob-
ject as a member of the class. Of course, you need to add an import statement to the SketcherFrame class
for javax.swing.JToolbar .
To add the toolbar to the application window, you need to add the following statement after the existing
code in the SketcherFrame constructor:
getContentPane().add(toolBar, BorderLayout.NORTH);
This adds the (currently 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. You add a JToolBar object
to a Container using the BorderLayout manager because it is normally positioned at one of the four sides
of a component. The other three sides of the content pane would be identified by the SOUTH , EAST , and WEST
constants in the BorderLayout class. An empty toolbar is not much use so let's see how you add buttons to
it.
Adding Buttons to a Toolbar
The JToolBar class inherits the add() methods from the Container class, so you can create JButton ob-
jects and add them to the toolbar using this method. The JButton class defines a constructor that accepts
an argument of type Action , and creates a button based on the Action object that is passed to it. You can
Search WWH ::




Custom Search