Adding Keyboard Shortcuts

You’ve already seen how adding a separator bar to a menu can make a drop-down more visually pleasing, but users expect another professional touch from a menu system—the ability to access the menu items via keyboard keystroke combinations.

How do I do that?

SWT provides two approaches to assigning keyboard combinations to menu items. The approach you use depends upon which of the two keyboard shortcut types you wish to provide.

The first shortcut type is a single-key mnemonic that activates the menu if—and only if—that menu item is visible (i.e., it is one of the high-level menu items that appear on the menu bar or one of the menu items that appear when a menu is in its dropped-down state). It’s easy to set this type of shortcut; just add an ampersand before the menu item text when calling the setText( ) method:

Note

You should consult guidelines for your target platform to determine the generally accepted keyboard shortcuts for particular functionality and design your menu to conform to those standards.

file.setText("&File");

Tip

This type of keyboard shortcut depends upon the operating system to function. The results you get may vary from system to system. For example, on some versions of Windows you will see the F in File underlined at all times. On other versions, the F will be underlined only when the ALT key is pressed. On Windows XP, it could be either, depending on user settings. You must remember to execute your code on all target platforms to test ...

Get SWT: A Developer's Notebook 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.