Java Reference
In-Depth Information
Menus in Java are supported by three components that work in conjunction with each
other:
JMenuItem
—An item on a menu
n
JMenu
—A drop-down menu that contains one or more
JMenuItem
components,
other interface components, and
separators
, lines displayed between items
n
JMenuBar
—A container that holds one or more
JMenu
components and displays
their names
n
A
JMenuItem
component is like a button and can be set up using the same constructor
methods as a
JButton
component. Call it with
JMenuItem(
String
)
for a text item,
JMenuItem(
Icon
)
for an item that displays a graphics file, or
JMenuItem(
String
,
Icon
)
for both.
The following statements create seven menu items:
JMenuItem j1 = new JMenuItem(“Open”);
JMenuItem j2 = new JMenuItem(“Save”);
JMenuItem j3 = new JMenuItem(“Save as Template”);
JMenuItem j4 = new JMenuItem(“Page Setup”);
JMenuItem j5 = new JMenuItem(“Print”);
JMenuItem j6 = new JMenuItem(“Use as Default Message Style”);
JMenuItem j7 = new JMenuItem(“Close”);
A
JMenu
container holds all the menu items for a drop-down menu. To create it, call the
JMenu(
String
)
constructor with the name of the menu as an argument. This name
appears on the menu bar.
After you have created a
JMenu
container, call its
add(
JMenuItem)
to add a menu item to
it. New items are placed at the end of the menu.
The item you put on a menu doesn't have to be a menu item. Call the
add(
Component
)
method with a user interface component as the argument. One that often appears on a
menu is a check box (the
JCheckBox
class in Java).
To add a line separator to the end of the menu, call the
addSeparator()
method.
Separators are often used to visually group several related items on a menu.
You also can add text to a menu that serves as a label of some kind. Call the
add(
String
)
method with the text as an argument.
Using the seven menu items from the preceding example, the following statements create
a menu and fill it with all those items and three separators: