Search code examples
javakey-bindingskeystroke

How to use the getKeyStroke(String s) method?


Link to the JavaDoc

I am trying to get an event when a key is released. I've tried formatting the String like it says to in the docs but it just makes that key unresponsive. Here is the working line of code:

getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);

Now I want to make it do something when I release the key, so attempting to follow the format from the doc, I've tried the following lines individually but they all make the key unresponsive:

1. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | pressed"), MOVE_DOWN);
2. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | released"), MOVE_DOWN);
3. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | true"), MOVE_DOWN);
4. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | false"), MOVE_DOWN);
5. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN, true"), MOVE_DOWN);
6. getInputMap(IFW).put(KeyStroke.getKeyStroke("VK_DOWN, false"), MOVE_DOWN);
7. getInputMap(IFW).put(KeyStroke.getKeyStroke("KeyEvent.VK_DOWN, false"), MOVE_DOWN);

You probably get the point... I have no idea how to format the String for this and have ran into a brick wall.

  1. How am I supposed to format the String for this?
  2. I saw that there are other methods, would it be better for me to use one of those instead, and how?

I feel like getKeyStroke(char keyChar, boolean onKeyRelease) is my best bet, but it says it's deprecated so should I totally avoid using that one?


Solution

  • Its documentation seems to be pretty clear. We can correct your example with the following:

    getInputMap(IFW).put(KeyStroke.getKeyStroke("pressed DOWN"), MOVE_DOWN);
    getInputMap(IFW).put(KeyStroke.getKeyStroke("released DOWN"), MOVE_DOWN);
    

    Note that the following is equivalent to "pressed DOWN":

    getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);