Java Reference
In-Depth Information
Creating Menus
Most applications contain a menu bar with commands that a user can click to
display a menu; each menu, in turn, includes commands that a user can click to
perform certain actions. Table 6-3 lists Java's menu components. The MenuBar
component is used to construct an instance of a menu bar. The Menu compo-
nent with its Menu() constructor method creates a new menu command on the
menu bar using the specified label. A second boolean argument indicates
whether or not the menu can be implemented as a tear-off menu , which
remains on the screen after the user releases the mouse button. On platforms
that do not support tear-off menus, the tear-off property is ignored. The
MenuItem component adds a command to a previously declared Menu
component, thus resulting in a new command on the drop-down menu. Each
of the Java menu components has an associated constructor method, as shown
in Table 6-3.
Table 6-3 Java Menu Components
MENU COMPONENT
DESCRIPTION
CONSTRUCTOR METHOD
MenuBar
creates a menu bar
MenuBar mnuBar = new MenuBar();
Menu
creates a menu bar
Menu mnuEdit = new Menu("Edit",
command
true);
MenuItem
creates a command
MenuItem mnuEditCopy = new
on a menu
MenuItem("Copy");
After the menu components are constructed, programmers use a variety of
methods to assign and populate the menus. Table 6-4 displays some of the more
common methods related to menus.
Table 6-4
Menu Methods
METHOD
DESCRIPTION
EXAMPLE
setMenuBar()
automatically displays a previously
setMenuBar(myMenu);
constructed menu bar at the top of the
Frame
add()
adds a command to a menu bar or menu
myMenu.add(mnuHelp);
mnuHelp.add(mnuHelpAbout);
addActionListener()
makes the menu item clickable
mnuEditCut.addActionListener(this);
setActionCommand()
sets a String to represent the action of
mnuEdit.setActionCommand("Edit");
the menu
remove()
removes a menu item from a menu bar
remove(mnuTools);
or menu
insertSeparator()
inserts a horizontal separator line at the
mnuTable.insertSeparator(1);
index position
 
Search WWH ::




Custom Search