up previous next contents
Up: java-on-mac Previous: Putting your application name Next: (Old approach) Handling the   Contents

Converting Control keystrokes to Command keystrokes

When you look at my drop-down menu items you can see the ^ symbol next to some of the menu items, such as S for the Save menu item. On the Mac these items should show [Command] symbols instead of [Control] symbols, and I'll fix these in my application next.

Because I'd never really coded for the Mac before I took a usual shortcut when declaring my accelerator keys. As an example, the code I used for my save accelerator key is shown here:

fileSaveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 
                                KeyEvent.CTRL_MASK, false));

Unfortunately these keystrokes aren't correct for Mac OS X. Figure 6.1 shows what the File menu looks like if I don't change my Java code:

Figure 6.1: The File menu shows my current [Control] setup.
Image 4-control-keys

To make this code more platform-neutral, and more specifically to work as desired on Mac OS X, I change that code to this code:

fileSaveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 
                                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

Testing this from the keyboard, it works great, changing my [Control][s] accelerator to [Command][s]. And it also looks right in the menu (see Figure 6.2), and I'm happy.

Figure 6.2: After the KeyStroke code change the File menu shows the [Command] key.
Image 5-command-keys