键绑定 - 信息。关键发布

时间:2013-12-01 11:28:44

标签: java swing key-bindings

我正在制作一个游戏,当我按下右键时,我的船开始旋转,这很好。 但是当我发布密钥时,我无法弄清楚如何获取信息。

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发布有关键事件吗?或者除了Keystroke对象之外还有什么东西可以使用? 我正在使用一个关键的监听器,但我遇到了一个问题,它无法正确检测到2个以上的按键,所以我去了键绑定。

对不起,如果这是重复的,我看看了。 任何帮助将非常感激。干杯

1 个答案:

答案 0 :(得分:1)

我在另一个堆栈溢出问题上找到了答案。 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"));

感谢您的帮助。