Assigning Keyboard Equivalents to Menu Items
Many Mac OS applications allow the user to select a menu item by entering a special key combination, such as the Command key followed by a letter or number. Such combinations are called keyboard equivalents (or, sometimes, shortcut keys). For example, many Mac OS applications have assigned the keyboard equivalent Command-o to the Open File menu item. Entering this key combination functions exactly as if the user selected the Open File menu item with the mouse.If you want to assign keyboard equivalents to menu items in your Java application, you can do so using the
SetMenuItemCmdKey
method in the classcom.apple.mrj.MRJMenuUtils
.
The
- IMPORTANT
- Future versions of MRJ, which implement Sun's JDK 1.1 standards, will let you assign keyboard equivalents by binding
MenuAccelerator
objects to a menu item, so you do not need to useSetMenuItemCmdKey
.![]()
SetMenuItemCmdKey
method allows you to assign a keyboard equivalent of the form "Command-character" to a menu item. TheSetMenuItemCmdKey
method is overloaded; you can specify the menu item by referencing the menu item by name or by menu name and menu index. Listing 1-7 shows code that creates items in a menu and assigns them keyboard equivalents.Listing 1-7 Assigning a keyboard equivalent to a menu item.
import com.apple.mrj.*; import java.io.*; import java.awt.*; ... class MenuTest extends Frame { MenuTest() { MenuBar mb = new MenuBar(); Menu menu = new Menu("Menu"); menu.add("Hop"); menu.add("Skip"); menu.add("Jump"); mb.add(menu); setMenuBar(mb); MRJMenuUtils.setMenuItemCmdKey(menu, 0, '1'); MRJMenuUtils.setMenuItemCmdKey(menu, 1, '2'); MRJMenuUtils.setMenuItemCmdKey(menu, 2, '3'); show(); } public boolean handleEvent(Event eve) { if (eve.id == Event.ACTION_EVENT) System.out.println(eve); return false; } }This code creates a menu namedMenu
which has three menu items associated with it:Hop
,Skip
, andJump
. It then assigns each a keyboard equivalent. For example, entering Command-1 would select the menu itemHop
. The keyboard equivalent appears in the menu item next to the item name.The rest of the code is a simple event handler that traps an event (that is, the selection of a menu item) and prints the contents of the Apple Event record to the standard output.
Although you can choose any letter or number to go with the Command key, most Mac OS applications have certain keyboard equivalent conventions, which you should follow. Table 1-2 shows some of the more common conventions.
For more information about keyboard equivalents, see the "Menu Manager" chapter of Inside Macintosh: Macintosh Toolbox Essentials.