Java Reference
In-Depth Information
Fixing the Color Menu Checks
One way to deal with the problem is to make the listener object for a color menu item set the checks for
all the menu items. You could code this in the ColorListener class as:
class ColorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
elementColor = color;
// Set the checks for all menu items
redItem.setState(color.equals(Color.RED));
greenItem.setState(color.equals(Color.GREEN));
blueItem.setState(color.equals(Color.BLUE));
yellowItem.setState(color.equals(Color.YELLOW));
}
// Rest of the class as before...
}
This calls the setState() method for each menu item. If the argument is true the checkmark is set,
and if it is false , it isn't. Clearly this will only set the checkmark for the item that corresponds to the
color referenced by color . This is quite straightforward but there is a better way.
A ButtonGroup object works with JCheckBoxMenuItem objects because they have
AbstractButton as a base class. Therefore we could add these menu items to their own button group
in the SketchFrame constructor, and it will all be taken care of for us. The ButtonGroup object
tracks the state of all of the buttons in the group. When any button is turned on, all the others are turned
off, so only one button in the group can be on at one time. So add the following code - it could go
anywhere after the items have been created but place it following the code that adds the items to the
Color menu for consistency with the element type code.
ButtonGroup colors = new ButtonGroup(); // Color menu items button group
colors.add(redItem);
colors.add(yellowItem);
Search WWH ::




Custom Search