Why does KeyStroke.getKeyStroke('s', KeyEvent.ALT_MASK) create an Alt-F4 keybinding?

244 views Asked by At

Running the following:

    KeyStroke ks1 = KeyStroke.getKeyStroke('s', KeyEvent.ALT_MASK);
    KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.ALT_MASK);
    KeyStroke ks3 = KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_MASK);

    System.out.println(ks1);
    System.out.println(ks2);
    System.out.println(ks3);

Results in:

    alt pressed F4
    alt pressed S
    alt pressed F4
2

There are 2 answers

0
BenCole On

This is because:

  • the int value for the char 's' is 115
  • and the int value of KeyEvent.VK_F4 is also 115

meaning that k1 and k3 are functionally the same.

5
Durandal On

There is no method getKeyStroke(char, int), thus the compiler widened your char 's' to an int and called getKeyStroke(int, int). The latter expects a virtual key code, not a unicode character.

Since (int) 's' widens to the int 115 wich coincidences with VK_F4, its doing exactly what you told it to do: Create a keybinding with VK_F4 and mask ALT.

Basically what happened is, you wanted to create a keybinding for char 's', but the compiler chose to create a keybinding for int 115. Its a simple mistake of assuming an overload that does not exist but a compatible, semantically different, overload being substituted by the compiler.