Reputation: 165
I want to add shortcut keys in Java Swing Menubar. Below is what I have tried.
jMenuItem1.setText("Create");
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK));
Here I want three KeyEvent.VK_C, KeyEvent.CTRL_MASK
, and KeyEvent.SHIFT_MASK
.
Upvotes: 3
Views: 8331
Reputation: 15
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.
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));
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).
Upvotes: 0
Reputation: 330
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));
Upvotes: 6
Reputation: 1258
KeyStroke.getKeyStroke(KeyEvent.VK_C, 21);
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/KeyStroke.html#getKeyStroke(int, int)
Read about the modifiers and you'll know what the 21 (or 2 and the 1) is for...
Upvotes: 3
Reputation: 1346
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK+ALT_MASK)
Upvotes: 7