Java Reference
In-Depth Information
If you recompile
Sketcher
once more, you can run the application again to try out the menus. If you ex-
tend the File menu by clicking on it, you see that it has the menu items that you have added. The window
is shown in
Figure 17-37
.
Now if you extend the Elements menu it should appear with the Line and Blue items checked.
How It Works
You have defined the fields that store references to the menu items for the drop-down menus as private
members of the class. For the File menu, the menu items are of type
JMenuItem
. In the Element menu
the items select a type of shape to be drawn, and because these are clearly mutually exclusive, you use
objects of type
JRadioButtonMenuItem
for them. You would normally use objects of the same type for
the element color menu items, but to try it out you are using the
JCheckBoxMenuItem
type.
To create the items in the File menu, you pass the
String
object for the label for each menu item to the
add()
method and leave it to the
JMenu
object to create the
JMenuItem
object. The
add()
method returns
a reference to the object that it creates and you store the reference in one of the fields you have defined
for that purpose. You need access to the menu item objects later when you add code to service events that
arise from the user clicking a menu item.
The first group of Elements menu items are
JRadioButtonMenuItem
objects, and you create each of
these in the argument to the
add()
method. To ensure only one is checked at a time, you 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. To make Line the default element type and Blue the default
color, you set both of these as checked by specifying
true
as the second argument to the constructor.
The other items are unchecked initially because you have specified the second argument as
false
. You
could have omitted the second argument to leave these items unchecked by default. It then means that
you need to remember the default to determine what is happening, so it is better to set the checks expli-
citly.
You can see the effect of the
addSeparator()
method from the
JMenu
class. It produces the horizontal
bar separating the items for element type from those for color. If you select any of the unchecked element
type items on the Elements drop-down menu, they are checked automatically, and only one can appear
checked. More than one of the color items can be checked at the moment, but you add some code in the
next chapter to make sure only one of these items is checked at any given time.