I am now working on adding some global key shortcuts to my application.
First, I've written a method to translate native modifier codes to swing's modifier codes, added a global native hook, but it did not work. Than, I've added a print-statemenet and encountered an unexpected result.
Code:
int m=KeyEvent.SHIFT_DOWN_MASK|KeyEvent.CTRL_DOWN_MASK|KeyEvent.ALT_DOWN_MASK;
System.out.println(m+" "+KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT,m).getModifiers());
Output: 704 715
.
So... Why? Why modifiers set are not what getter returns?
I reckon, it should return 704 704
.
Years ago, someĀ¹ old modifiers ALT_MASK
, CTRL_MASK
, META_MASK
, and SHIFT_MASK
were replaced by new ones: ALT_DOWN_MASK
, CTRL_DOWN_MASK
, META_DOWN_MASK
, and SHIFT_DOWN_MASK
.
The old ones were deprecated (Java 9) but are still available.
Calling KeyStroke.getKeyStroke(int, int)
will add the corresponding missing modifiers to the given modifiers, so both, the old modifiers or the new modifiers can be used.
704
= 0b10_1100_0000
= 512 | 128 | 64
715
= 0b10_1100_1011
= 512 | 128 | 64 | 8 | 2 | 1
From the javadoc:
public static final int ALT_MASK = 8 public static final int CTRL_MASK = 2 public static final int SHIFT_MASK = 1
Relevant OpenJDK source code: AWTKeyStroke:771
1 the modifiers list is not complete, more were affected