Java Reference
In-Depth Information
// Create Elements menu buttons
for(TypeAction action:typeActions){
addToolbarButton(action); // Add the toolbar button
}
}
Directory "Sketcher 8 with toolbar buttons and menu icons"
Both sets of buttons are created from the corresponding Action objects in the same way. If you recompile
Sketcher, you should see a more comprehensive toolbar when you execute it. However, there's a problem. If
you click a toolbar button for a new color or a new element type, the menu item checks don't get updated.
Fixing Menu Checks
You did not store the menu items or the toolbar buttons. Updating the status of menu items you have not
stored is a little tricky, but possible. The key to fixing the selected status of the menu items lies with the
Action objects you used to create them. You used the same Action objects to create the toolbar buttons.
If you can use this to match the toolbar button that was clicked with the corresponding menu item, you are
almost there. I explain how it works and then give you the code.
The actionPerformed() method for an Action object receives an event as an object of type Ac-
tionEvent that records information about the source of the event. You can get a reference to the menu
item or toolbar button that originated the event by calling getSource() for the ActionEvent object. The
getSource() method returns a reference of type Object , but you can easily determine whether or not it is
a JButton object using the instanceof operator. A JMenu object has a getItem() method that returns the
menu item at a given index position. You have the elementMenu and colorMenu objects available so this
gives you a way to get to the menu items in the drop-down.
Both menu item or toolbar button objects provide a getAction() method that returns a reference to the
Action object that originated them. Thus you can get the Action object for a JButton that originates an ac-
tion event and compare it with the Action objects for the menu items. If you have a match, then the toolbar
button that corresponds to the menu item that has the same Action object was clicked.
Applying all that I have discussed about actions to the code that sets menu item checks when a color
toolbar button is clicked looks like this:
public void actionPerformed(ActionEvent e) {
elementColor = color;
setChecks(colorMenu, e.getSource());
}
Directory "Sketcher 8 with toolbar buttons and menu icons"
This method is in the ColorAction class. It passes the JMenu item for the menu and a reference to the
object that originated to a new method that sets the menu checks when appropriate. Using a separate method
Search WWH ::




Custom Search