Java Reference
In-Depth Information
Try It Out - Removing Menu Item Icons
We just need to add one statement to addMenuItem() method in the SketchFrame class to remove
the icons for all the menu items, like this:
private JMenuItem addMenuItem(JMenu menu, Action action) {
JMenuItem item = menu.add(action); // Add the menu item
KeyStroke keystroke = (KeyStroke)action.getValue(action.ACCELERATOR _ KEY);
if(keystroke != null)
item.setAccelerator(keystroke);
item.setIcon(null); // Remove the icon
return item; // Return the menu item
}
When you run Sketcher with this modification to SketchFrame , you should see the menu items
without icons.
How It Works
When we construct each of the menu items using our helper method addMenuItem() we remove the
icon from the JMenuItem that is created by passing null to its setIcon() method. Thus none of the
menu item objects has an icon associated with it. Of course, the toolbar buttons are unaffected and
retain the icons defined by the Action objects they are created from.
Adding Tooltips
I'm sure you have seen tooltips in operation. These are the little text prompts that appear automatically
when you let the mouse cursor linger over certain GUI elements on the screen for a second or two.
They disappear automatically when you move the cursor. I think you will be surprised at how easy it is
to implement support for tooltips in Java.
The secret is in the Action objects that we are using. Action objects have a built-in capability to store
tooltip text because it is already provided for with the SHORT _ DESCRIPTION key that is defined in the
interface. All we have to do is store the tooltip text in our inner classes that are derived from
AbstractAction . The tooltip will then be automatically available on the toolbar buttons that we
create. Let's work through our Action classes and provide for tooltip text.
Try It Out - Implementing Tooltips
We can provide for tooltip text in each of our inner classes by adding constructors with an extra
parameter for it. We need two additional constructors in the FileAction class, one for when the
Action item has an accelerator key, and the other for when it doesn't. The definition of the first new
FileAction class constructor will be:
FileAction(String name, KeyStroke keystroke, String tooltip) {
this(name, keystroke); // Call the other constructor
if(tooltip != null) // If there is tooltip text
putValue(SHORT _ DESCRIPTION, tooltip); // ...squirrel it away
}
Search WWH ::




Custom Search