Java Reference
In-Depth Information
Now if you extend the Elements menu it should appear as shown with the Line and Blue items checked.
How It Works
We have defined the variables storing references to the menu items for the drop-down menus as private
members of the class. For the File menu items they are of type JMenuItem . In the Element menu the
items select a type of shape to be drawn, and, as these are clearly mutually exclusive, we are using type
JRadioButtonMenuItem for them. We could use the same type for the element color items, but in
order to try it out we are using the JCheckBoxMenuItem type.
To create the items in the File menu, we pass the String for the label for each to the add() method
and leave it to the JMenu object to create the JMenuItem object.
The first group of Elements menu items are JRadioButtonMenuItem objects and we create each of these
in the argument to the add() method. To ensure only one is checked at a time, we also add them to a
ButtonGroup object. The color menu items are of type JCheckBoxMenuItem so the current selection is
indicated by a check mark on the menu. We will make Line the default element type and Blue the default
color, so we set both of these as checked by specifying true as the second argument to the constructor.
The other items will be unchecked initially because we have specified the second argument as false .
We could have omitted the second argument to leave these items unchecked by default. It then means
that you need to remember the default in order to determine what is happening. It is much better to set
the checks explicitly.
Search WWH ::




Custom Search