Mac Java keystroke - How to handle the Apple (command) key with Java on Mac OS X

Java Mac keystroke FAQ: How do I write Java KeyStroke code for Mac OS X systems?

When I switched from "Java programming on Windows" (or Linux) to "Java programming on a Mac", I quickly learned that I was going to have to change the way I bound my keystrokes for handling key-driven events (things like keystroke-driven popup menus, mnemonics, or accelerator keys). On Windows systems I used to write key-binding code like this:

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK);

but once I started doing more Java Swing programming on Mac OS X, I realized I needed to change that line of code to look like this:

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

Java KeyStrokes and Mac menubar images

As a quick look at what this change to Mac Java KeyStroke handling does, here are two images of my Mac menubar that demonstrate the difference from changing this single line of Java code. First, when I use this older line of Java code:

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK);

I see that OS X is expecting me to use the Control key:

If you're a Mac user, you know that's not correct for the Mac look and feel.

So, when I switch to this second (corrected) version of my Mac Java KeyStroke code:

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

I can see from the following image that OS X is now ready to work with the Apple/command key:

(Sorry, those images are a little blurry.)

Mac Java keystrokes - Handling the Command key

I hope this short tutorial on handling the Mac Command key when writing Java/Swing KeyStroke code has been helpful. As you can see, a minor change to your approach makes your Java/Swing application look and feel just like a native Mac application.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.