DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 9.11 Creating Menu Item Accelerators and Mnemonics

9.11.1 Problem

You need to add keyboard access to your menu items.

9.11.2 Solution

In SWT, you can support menu item accelerators and mnemonics. To create an accelerator, use the menu item's setAccelerator method; to create a mnemonic, insert an ampersand (&) in the menu item's caption just before the character you want to use as the mnemonic. (Make sure it's a unique mnemonic among those that will be visible at the same time.)

9.11.3 Discussion

Mnemonics are keys you can access as part of a key combination to select a menu item. For example, if a menu item's mnemonic is S, you can access that item by pressing Alt-S in Windows or Apple-S in Mac OS X. You can use a mnemonic when the corresponding menu is already open.

Accelerators, on the other hand, can be used at any time, regardless of whether the corresponding menu is open. As an example, here's how you can give a menu item the mnemonic S and the accelerator Ctrl-S:

menuItem.setText("&Spell Check\tCtrl+S");
menuItem.setAccelerator (SWT.CTRL + 'S');

9.11.4 See Also

Recipe 9.7 on creating a menu system; Recipe 9.8 on creating text menu items; Recipe 9.9 on creating image menu items; Recipe 9.10 on creating radio menu items; Recipe 9.12 on enabling and disabling menu items; Chapter 8 in Eclipse (O'Reilly).

    Previous Section  < Day Day Up >  Next Section