From the Java Menu Tutorial:
To specify an accelerator you must use a KeyStroke object, which combines a key (specified by a KeyEvent constant) and a modifier-key mask (specified by an ActionEvent constant).
The referenced "modifier-key mask" is created from multiple ActionEvents via bitwise operations, so the bitwise OR specifying multiple events in the setAccelerator()
method does the same thing.
On Windows Only:
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));
Cross-platform:
To enable this cross-platform (i.e. to use the Command
button on a Mac instead of Control
), simply replace the java.awt.Event.CTRL_MASK
with:
@SuppressWarnings("deprecation")
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); // Java 9 or older
or
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); // Java 10 or newer
for a final setAccelerator that looks like
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() |
java.awt.Event.SHIFT_MASK));
On a Mac you'll also notice that the Accelerator text in the menu itself shows the CMD symbol, too, while on Windows it'll still show CTRL (e.g. CMD+S vs. CTRL+S).