Java Reference
In-Depth Information
in which they are added. The following code, taken from the constructor in Display
17.14, creates a new
JMenu
object named
colorMenu
and then adds a
JMenuItem
labeled
"Red"
. Other menu items are added in a similar way.
JMenu colorMenu =
new
JMenu("Add Colors");
JMenuItem greenChoice =
new
JMenuItem("Green");
greenChoice.addActionListener(
this
);
colorMenu.add(greenChoice);
Note that, just as we did for buttons in Display 17.11, in Display 17.14 we have
registered the
this
parameter as an action listener for each menu item. Defining
action listeners and registering listeners for menu items are done in the exact same way
as for buttons. In fact, the syntax is even the same. If you compare Display 17.14 and
Display 17.11, you will see that the definition of the method
actionPerformed
is the
same in both classes.
You add a
JMenuItem
to an object of the class
JMenu
using the method
add
in
exactly the same way that you add a component, such as a button, to a container
object. Moreover, if you look at the preceding code, you will see that you specify a
string for a
JMenuItem
in the same way that you specify a string to appear on a button.
A
menu bar
is a container for menus, typically placed near the top of a window-
ing interface. You add a menu to a menu bar using the method
add
in the same way
that you add menu items to a menu. The following code from the constructor in
Display 17.14 creates a new menu bar named
bar
and then adds the menu named
colorMenu
to this menu bar:
listeners
menu bar
JMenuBar bar =
new
JMenuBar();
bar.add(colorMenu);
There are two different ways to add a menu bar to a
JFrame
. You can use the
method
setJMenuBar
, as shown in the following code from the constructor in Dis-
play 17.14:
setJMenuBar(bar);
This sets an instance variable of type
JMenuBar
so that it names the menu bar named
bar
. Saying it less formally, this adds the menu bar named
bar
to the
JFrame
and
places the menu bar at the top of the
JFrame
.
Alternatively, you can use the
add
method to add a menu bar to a
JFrame
(or to any
other container). You do so in the same way that you add any other component, such as
a label or a button. An example of using
add
to add a
JMenuBar
to a
JFrame
is given in
the file
MenuAdd.java
on the accompanying CD.
extra code
on CD