Java Reference
In-Depth Information
combination the menu is displayed. You can add shortcuts for the File and Elements menu items by adding
the following statements after you add the menu items to the menu bar:
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut
The setMnemonic() method is inherited from the AbstractButton class, so all subclasses of this class
inherit this method. The argument is a character from the label for the item that is to be the shortcut character
— under Windows, the File menu would then pop up if you key Alt+F. The effect of setMnemonic() is to
implement the shortcut and underline the shortcut character letter in the menu label. The shortcut for each
menu on the menu bar must be a unique key combination.
An accelerator is a key combination that you can enter to select an item from a drop-down menu without
having to go through the process of displaying the menu. Under Windows, the Ctrl key is frequently used
in combination with a letter as an accelerator for a menu item, so Ctrl+L might be the combination for the
Line item in the Elements menu. To define the accelerator for a menu item, you call the setAccelerator()
method for the object that encapsulates the menu item. For example, for the Line menu item you could write
the following:
lineItem.setAccelerator(KeyStroke.getKeyStroke('L', InputEvent.CTRL_DOWN_MASK));
The javax.swing.KeyStroke class defines a keystroke combination. The static method
getKeyStroke() in the KeyStroke class returns the KeyStroke object corresponding to the arguments.
The first argument is a character in the keystroke combination and the second argument specifies one
or more modifier keys. Only use uppercase letters to identify a letter for a keystroke. Lowercase letters
select the non-alphabetic keys, such as the numeric keypad and the function keys. The modifier keys are
specified as a combination of single-bit constants that are defined in the InputEvent class that appears
in the java.awt.event package. The InputEvent class defines constants that identify control keys on
the keyboard and mouse buttons. In this context, the constants you are interested are SHIFT_DOWN_MASK ,
ALT_DOWN_MASK , META_DOWN_MASK , and CTRL_DOWN_MASK . If you want to express a combination of the Alt
and Ctrl keys for example, you can combine them as shown in the following expression:
InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK
Of course, when you add accelerators for menu items, if the accelerators are to work properly, you must
make sure that each accelerator key combination is unique. Let's see how this works in practice.
TRY IT OUT: Adding Menu Shortcuts
You can add some shortcuts to Sketcher by amending the statements that add the items to the File menu
in the SketcherFrame class constructor:
// Frame for the Sketcher application
import javax.swing.*;
Search WWH ::




Custom Search