Kernel
Kernel

Reputation: 165

How to add three Shortcut keys ( Ctrl + Shift + C) in Java Swing Menubar?

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

Answers (4)

smackerman
smackerman

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.

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

Upvotes: 0

Siddhartha Sadhukhan
Siddhartha Sadhukhan

Reputation: 330

jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));

Upvotes: 6

Bradley Odell
Bradley Odell

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

Avi
Avi

Reputation: 1346

jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK+ALT_MASK)

Upvotes: 7

Related Questions