Search code examples
javaswingkey-bindingskeystroke

Listening for a slash keystroke without knowing the modifier key in Swing


I am trying to listen to the keystroke for a slash character in a Swing component. Registering it with

component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, 0), myAction);

works, when using an english keyboard layout (where a slash is a single keystroke). However when using a german keyboard layout, a slash is entered via shift-7 and the obove code doesn't work!

Now what is the correct way to listen for exactly a slash character, instead of a combination of key?


Solution

  • Your current KeyStroke listens for the keyPressed event.

    Maybe you can use:

    KeyStroke slash = KeyStroke.getKeyStroke("typed /");  // or
    KeyStroke slash = KeyStroke.getKeyStroke('/'); 
    

    This should listen for the keyTyped event which should work for KeyStrokes that actually generated a typed character that can be added to a text field for example.