Reputation: 459
Short Version: How do I determine when a KeyBind key has been released in similar functionality to a KeyListener keyReleased() event?
Long Version: I am experimenting a bit with making a very simple game, and I was using several KeyListeners to track my keyboard input. However, as I added more complicated features, I began to encounter issues with the keyboard input not receiving proper focus and thus no keyboard input was being received.
Then I read about KeyBinds. While the KeyBinds functionality fixed my focus issue, for my game I was wanting to change a value based off whether a key was pressed or not. I can get the value to change through pressing the key, but I don't know how to detect when the key is released. The KeyListener had a separate KeyPressed and KeyReleased method, but that won't work correctly due to component focusing issues.
Relevant Code: I don't have a lot of code to share because the input was simply needed to call one of two methods which are set up in another class (and I was testing KeyBinds). But here is the relevant KeyBind code anyway:
Action myAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("testing action output");
}
};
actionMap = getActionMap();
inputMap = getInputMap(condition);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "leftArrow");
actionMap.put("leftArrow", myAction);
And here's the code I was using with KeyListener (again, very little since I just call a method)
addKeyListener(new KeyListener()
{
@Override
public void keyPressed(KeyEvent e)
{
racquetClass.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e)
{
racquetClass.keyReleased(e);
}
@Override
public void keyTyped(KeyEvent e)
{
}
});
Thanks in advance to any and all help that can be provided.
Upvotes: 2
Views: 491
Reputation: 324147
but I don't know how to detect when the key is released.
You need to create a separate Key Binding:
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "leftArrowReleased");
actionMap.put("leftArrowReleased", myReleasedAction);
Upvotes: 3