img
Menu Bars and Menus
A top-level window can have a menu bar associated with it. A menu bar displays a list of
top-level menu choices. Each choice is associated with a drop-down menu. This concept is
implemented in the AWT by the following classes: MenuBar, Menu, and MenuItem. In
general, a menu bar contains one or more Menu objects. Each Menu object contains a list of
MenuItem objects. Each MenuItem object represents something that can be selected by the
user. Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created.
It is also possible to include checkable menu items. These are menu options of type
CheckboxMenuItem and will have a check mark next to them when they are selected.
To create a menu bar, first create an instance of MenuBar. This class only defines the
default constructor. Next, create instances of Menu that will define the selections displayed
on the bar. Following are the constructors for Menu:
Menu( ) throws HeadlessException
Menu(String optionName) throws HeadlessException
Menu(String optionName, boolean removable) throws HeadlessException
Here, optionName specifies the name of the menu selection. If removable is true, the
menu can be removed and allowed to float free. Otherwise, it will remain attached to
the menu bar. (Removable menus are implementation-dependent.) The first form creates
an empty menu.
Individual menu items are of type MenuItem. It defines these constructors:
MenuItem( ) throws HeadlessException
MenuItem(String itemName) throws HeadlessException
MenuItem(String itemName, MenuShortcut keyAccel) throws HeadlessException
Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for this item.
You can disable or enable a menu item by using the setEnabled( ) method. Its form is
shown here:
void setEnabled(boolean enabledFlag)
If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is
disabled.
You can determine an item's status by calling isEnabled( ). This method is shown here:
boolean isEnabled( )
isEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise, it
returns false.
You can change the name of a menu item by calling setLabel( ). You can retrieve the
current name by using getLabel( ). These methods are as follows:
void setLabel(String newName)
String getLabel( )
Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the
current name.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home