Java Reference
In-Depth Information
Adding Menu Item Listeners
Events and listeners for menu items are handled in the exact same way as they are for buttons:
Menu items fire action events that are received by objects of the class
ActionListener
.
SYNTAX
JMenu_Item_Name
.addActionListener(
Action_Listener
);
EXAMPLE
redChoice.addActionListener(
this
);
Creating a Menu
A menu is an object of the class
JMenu
. You create a new menu in the usual way, as illustrated
by the following example. The string argument is the displayed text that identifies the menu.
JMenu colorMenu =
new
JMenu("Add Colors");
Adding Menu Items to a Menu
You use the method
add
to add menu items to a menu.
SYNTAX
JMenu_Name
.add(
JMenu_Item
);
EXAMPLE (
colorMenu
IS AN OBJECT OF THE CLASS
JMenu
)
colorMenu.add(redChoice);
Creating a Menu Bar
A menu bar is an object of the class
JMenuBar
. You create a new menu bar in the usual way,
as illustrated by the following example:
JMenuBar bar =
new
JMenuBar();
Adding a Menu to a Menu Bar
You add a menu to a menu bar using the method
add
as follows:
SYNTAX
JMenu_Bar_Name
.add(
JMenu_Name
);
EXAMPLE (
bar
IS AN OBJECT OF THE CLASS
JMenuBar
)
bar.add(colorMenu);
(continued)