Java Reference
In-Depth Information
toolBar.setBorder(BorderFactory.createCompoundBorder( // Toolbar border
BorderFactory.createLineBorder(Color.darkGray),
BorderFactory.createEmptyBorder(2,2,4,2)));
toolBar.setFloatable(false); // Inhibit toolbar floating
getContentPane().add(toolBar, BorderLayout.NORTH); // Add the toolbar
}
Now you should get the window with the toolbar that we showed at the beginning, with a nice neat
toolbar. You can see the color buttons in action since they will change the background color.
How It Works
The extra code in the inner class constructors stores an icon in each object if there is a GIF file with the
appropriate name in the
Images
subdirectory. We create each of the toolbar buttons by calling our
addToolBarButton()
helper method with an
Action
item corresponding to a menu item. The
helper method passes the
Action
object to the
add()
method for the
JToolBar
object to create a
JButton
object. It also adds a border to the button. The
addToolBarButton()
method returns a
reference to the button object in case we need it.
We have added a further statement to add a border to the toolbar. We use the
createCompoundBorder()
method to create a border with an outer border that is a single line, and
an inner border that is empty but inserts space around the inside of the outer border as specified by the
arguments. The arguments to
createEmptyBorder()
are the width in pixels of the border in the
sequence top, left, bottom and right.
Fixing the Menus
Things are perhaps still not quite as we would have them. If you take a look at the menus you will see
what I mean.
All of the menu items now have icons too. While this is a helpful cue to what the toolbar icons are,
maybe you would rather not have them as they look a little cluttered. We could get rid of the icons very
easily by modifying the menu items that are created by the
add()
method for the
JMenu
objects in the
addMenuItem()
method. The
JMenuItem
class has a
setIcon()
method that accepts a reference of
type
Icon
to set an icon for a menu item. If we want to remove the icon, we just pass
null
to it.