18.8. Adding a Toolbar

A toolbar is a bar, usually positioned below the menu bar, which contains a row of buttons that typically provides a more direct route to menu options. You could add a toolbar to the Sketcher program for the menu items that are likely to be most popular. Just so that you know where you are heading, the kind of toolbar you will end up with ultimately is shown in Figure 18-8.

Figure 18.8. Figure 18-8

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 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. Of course, you'll need to add an import statement to the SketchFrame 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 SketchFrame constructor:

getContentPane().add(toolBar, BorderLayout.NORTH);

This adds ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.