3

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.

Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
Kernel
  • 165
  • 4
  • 14
  • Have you tried the swing tutorial on the java website? – dann.dev Feb 22 '12 at 04:18
  • Please do remove that word BOSS from your question, the first thing comes to my mind is regarding JBOSS Application Server, moreover it doesn't gives a nice interpretation to your question. – nIcE cOw Feb 22 '12 at 05:07

4 Answers4

7
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK+ALT_MASK)
Avi
  • 1,231
  • 10
  • 23
6
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));
  • StackOverflow's best practices suggest to explain the proposed solutions. Posting just code is not a good thing, you should always explain WHY your solution works. – Massimiliano Kraus Jul 18 '17 at 14:57
3

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...

Bradley Odell
  • 1,248
  • 2
  • 15
  • 28
0

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).

smackerman
  • 17
  • 1
  • 6