Java Reference
In-Depth Information
Try It Out - A Button with an Icon
You can add the statement to create the icon for the Action object just before we create the toolbar button:
public SketchFrame(String title) {
// Constructor code as before...
openAction.putValue(Action.SMALL _ ICON, new ImageIcon ("Images/open.gif"));
JButton button = toolBar.add(openAction); // Add toolbar button
button.setBorder(BorderFactory.createRaisedBevelBorder());// Add button border
toolBar.setFloatable(false); // Inhibit toolbar floating
getContentPane().add(toolBar, BorderLayout.NORTH); // Add the toolbar
}
In fact you could put the statement anywhere after the openAction object is created, but here will be
convenient. If you recompile Sketcher and run it again, you should see the window below.
How It Works
The ImageIcon object that we store in our openAction object is automatically used by the add()
method for the toolBar object to add the icon to the button. Fortunately we don't get the label on the
toolbar button as well as the icon since the label is automatically inhibited by the presence of an icon. If
you look at the corresponding menu item though, we get both the label and the icon. This might not be
what you want so we will return to this point a little later in this chapter.
It would be better if we altered the inner classes that define the Action objects to add icons
automatically when a suitable .gif file is available. Let's try that now.
Try It Out - Adding All the Toolbar Buttons
We can modify the constructor for each inner class to add the corresponding icon. Here's how we can
implement this in the FileAction class:
FileAction(String name) {
super(name);
String iconFileName = "Images/" + name + ".gif";
if(new File(iconFileName).exists())
putValue(SMALL _ ICON, new ImageIcon(iconFileName));
}
Search WWH ::




Custom Search