Chapter 24: Using AWT Controls, Layout Managers, and Menus 737
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, andMenuItem.In
general, a menu bar contains one or moreMenuobjects. EachMenuobject contains a list of
MenuItemobjects. EachMenuItemobject represents something that can be selected by the
user. SinceMenuis a subclass ofMenuItem, a hierarchy of nested submenus can be created.
It is also possible to include checkable menu items. These are menu options of type
CheckboxMenuItemand will have a check mark next to them when they are selected.
To create a menu bar, first create an instance ofMenuBar. This class only defines the
default constructor. Next, create instances ofMenuthat will define the selections displayed
on the bar. Following are the constructors forMenu:
Menu( ) throws HeadlessException
Menu(StringoptionName) throws HeadlessException
Menu(StringoptionName, booleanremovable) throws HeadlessException
Here,optionNamespecifies the name of the menu selection. Ifremovableistrue, 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 typeMenuItem. It defines these constructors:
MenuItem( ) throws HeadlessException
MenuItem(StringitemName) throws HeadlessException
MenuItem(StringitemName, MenuShortcutkeyAccel) throws HeadlessException
Here,itemNameis the name shown in the menu, andkeyAccelis the menu shortcut for this item.
You can disable or enable a menu item by using thesetEnabled( )method. Its form is
shown here:
void setEnabled(booleanenabledFlag)
If the argumentenabledFlagistrue, the menu item is enabled. Iffalse, the menu item is
disabled.
You can determine an item’s status by callingisEnabled( ). This method is shown here:
boolean isEnabled( )
isEnabled( )returnstrueif the menu item on which it is called is enabled. Otherwise, it
returnsfalse.
You can change the name of a menu item by callingsetLabel( ). You can retrieve the
current name by usinggetLabel( ). These methods are as follows:
void setLabel(StringnewName)
String getLabel( )
Here,newNamebecomes the new name of the invoking menu item.getLabel( )returns the
current name.