9.11. Creating Menu Item Accelerators and Mnemonics
Problem
You need to add keyboard access to your menu items.
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.)
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');
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).
Get Eclipse Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.