Java Reference
In-Depth Information
JMenu colorMenu =
new
JMenu("Add Colors");
JMenuItem blueChoice =
new
JMenuItem("Blue");
blueChoice.addActionListener(
this
);
colorMenu.add(blueChoice);
Note that, just as we did for buttons in Display 17.11, in Display 17.14 we 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 Displays 17.14 and 17.11, you will
see that the definition of the method
actionPerformed
is the same in both classes.
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 windowing
interface. 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:
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.
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 Display 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 website.
extra code
on website
Menus
A
menu
is an object of the class
JMenu
. A choice on a menu is an object of the class
JMenuItem
. Menus are collected together in a
menu bar
(or menu bars). A menu bar is an
object of the class
JMenuBar
.
Events and listeners for menu items are handled in exactly the same way as they are
for buttons.