Search code examples
javaswingkeystroke

How to declare KeyStroke - pressed and released?


I want to know how to declare new KeyStroke - pressed and released? For example I can do:

KeyStroke.getKeyStroke("pressed F10");
KeyStroke.getKeyStroke("released F10");

But how to write in a way like this?:

KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0);

Solution

  • There is a method with an additional boolean argument for this

    KeyStroke.getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease)

    The method you discovered works on key press, so this:

    KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0);
    

    is equivalent to

    KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0, false);
    

    If you want to get this working on the release of F10, use

    KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0, true);