我正在制作一个游戏,当我按下右键时,我的船开始向右旋转,这很好。 但我不知道如何获取释放 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;
}
VK_Right 发布有关键事件吗?或者除了 Key Strike 对象之外还有其他东西可以使用吗? 我使用的是按键监听器,但遇到了一个问题,它无法正确检测超过 2 个按键,因此我进行了按键绑定(bind)。
抱歉,如果这是重复的,我已经看过了。 任何帮助将非常感激。干杯
最佳答案
我在另一个堆栈溢出问题上找到了答案。 Java KeyBindings: How does it work?
我将代码更改为
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"));
感谢您的帮助。
关于java - 键绑定(bind) - 信息。释放按键时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311636/