Reputation: 2928
I am making a game, when I press the right key my ship starts spinning right which is good. But I cannot figure out how to get information for when I release the key.
board.java
public Board()
{
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
helper = new Helper();
player = new Ship();
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0),
"PlayerRight");
this.getActionMap().put("PlayerRight",
new KeyBoardControl(player,"ArrowRight"));
isRunning = true;
gameLoop();
}
keyBoardControl.java
public class KeyBoardControl extends AbstractAction
{
public String key;
public Ship player;
public KeyBoardControl(Ship player ,String key)
{
this.player = player;
this.key = key;
}
@Override
public void actionPerformed(ActionEvent ae)
{
player.keyPressed(key);
}
}
Ship.java
public void keyPressed(String key)
{
//int key = e.getKeyCode();
// double angle = helper.getAngle(rotation - 90);
if (key.contentEquals("ArrowRight"))
{
dRotation = 7;
}
}
public boolean keyReleased(String key)
{
if (key.contentEquals("ArrowRight"))
{
dRotation = 0;
}
return true;
}
Is there a key event for VK_Right release? or is there something other than the Keystroke object to use? I was using a key listener but I had a problem where it would not detect over 2 key presses correctly so I went for key binding.
Sorry if this is a duplicate, I have had a look. Any help would be much appreciated. Cheers
Upvotes: 0
Views: 1854
Reputation: 2928
I found the answer on another stack overflow question. Java KeyBindings: How does it work?
I changed my code to
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0,false),
"PlayerRight");
this.getActionMap().put("PlayerRight",
new KeyBoardControl(player,"ArrowRight"));
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0,true),
"PlayerRightRelease");
this.getActionMap().put("PlayerRightRelease",
new KeyBoardControl(player,"ArrowRightRelease"));
Thanks for all the help.
Upvotes: 2