java - 键绑定(bind) - 信息。释放按键时

标签 java swing key-bindings

我正在制作一个游戏,当我按下右键时,我的船开始向右旋转,这很好。 但我不知道如何获取释放 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/

相关文章:

java - 通过jtable中的箭头键删除行选择

java - 我们如何在java中创建接口(interface)对象?

java - Autowiring 和 Spring 注入(inject)的问题

java - 将图像添加到 JOptionPane

java - JComboBox 当 getItemCount()>0 时显示空白区域

vim - 诊断 Vim 中的键绑定(bind)问题

Java:以一定角度移动对象并使用 KeyPress 改变角度

java - Travis CI 不使用 pom.xml 中提供的额外 Maven 存储库

java - 我如何在 Java 中实现使用不同类型的两个字段进行排序的元组优先级队列?

java - 将按钮放置在组合框下方