Java Reference
In-Depth Information
Expanded
submenu
Menu items
Separator
line
Fig. 22.6 | Test class for MenuFrame . (Part 2 of 2.)
Setting Up the File Menu
Lines 38-76 set up the File menu and attach it to the menu bar. The File menu contains an
About… menu item that displays a message dialog when the menu item is selected and an
Exit menu item that can be selected to terminate the application. Line 38 creates a JMenu and
passes to the constructor the string "File" as the name of the menu. Line 39 uses JMenu
method setMnemonic (inherited from class AbstractButton ) to indicate that F is the mne-
monic for this menu. Pressing the Alt key and the letter F opens the menu, just as clicking
the menu name with the mouse would. In the GUI, the mnemonic character in the menu's
name is displayed with an underline. (See the screen captures in Fig. 22.6.)
Look-and-Feel Observation 22.2
Mnemonics provide quick access to menu commands and button commands through the
keyboard.
Look-and-Feel Observation 22.3
Different mnemonics should be used for each button or menu item. Normally, the first letter
in the label on the menu item or button is used as the mnemonic. If several buttons or menu
items start with the same letter, choose the next most prominent letter in the name (e.g., x is
commonly chosen for an Exit button or menu item). Mnemonics are case insensitive.
Lines 42-43 create JMenuItem aboutItem with the text “ About... ” and set its mne-
monic to the letter A . This menu item is added to fileMenu at line 44 with JMenu method
add . To access the About... menu item through the keyboard, press the Alt key and letter
F to open the File menu, then press A to select the About... menu item. Lines 46-56 create
an ActionListener to process aboutItem 's action event. Lines 52-54 display a message
dialog box. In most prior uses of showMessageDialog , the first argument was null . The
purpose of the first argument is to specify the parent window that helps determine where
the dialog box will be displayed. If the parent window is specified as null , the dialog box
appears in the center of the screen. Otherwise, it appears centered over the specified parent
window. In this example, the program specifies the parent window with Menu-
Frame.this —the this reference of the MenuFrame object. When using the this reference
in an inner class, specifying this by itself refers to the inner-class object. To reference the
outer-class object's this reference, qualify this with the outer-class name and a dot ( . ).
Recall that dialog boxes are typically modal. A modal dialog box does not allow any
other window in the application to be accessed until the dialog box is dismissed. The dia-
logs displayed with class JOptionPane are modal dialogs. Class JDialog can be used to
create your own modal or nonmodal dialogs.
 
Search WWH ::




Custom Search