在java中按下多个键需要帮助

时间:2010-11-07 16:17:43

标签: java

我正在尝试使用Java编写类似于Mario的游戏,并且在他跑步时遇到问题。以下代码最终做的是,当用户按住右键并按下跳转按钮时,Mario基本上停止运行并跳转,因此它就像用户放开了右键并按下跳跃。

public void keyPressed(KeyEvent e) {
// here I keep track of what buttons the user pressed
    int keyCode = e.getKeyCode();

    if(keyCode == 37)
        pressedKeys[0] = true;
    else if(keyCode == 39)
        pressedKeys[1] = true;
    else if(keyCode == 68)
        pressedKeys[2] = true;

    // after I see what the user has pressed an action is carried out
    Thread t = new Thread(this);
    t.start();
}

public void performAction()
{
    // depending on what the user has pressed a certain action is performed
    if(pressedKeys[2]==true)
    {
        // changes the coordinates of the character itself
        // done in another thread so the background can continue
        // moving as the user holds down a direction
        Thread t = new Thread(mcControl);
        t.start();
    }
    if(pressedKeys[0]==true)
    {
        changeSprite();
        bg.moveImageForward();
    }
    if(pressedKeys[1]==true)
    {
        changeSprite();
        bg.moveImageBackward();
    }
}

public void run() {
    performAction();
}

2 个答案:

答案 0 :(得分:1)

if(keyCode == 37) 

与您的问题无关,但绝不使用这样的代码。大多数人都不知道这个神奇的数字意味着什么。

更好的方法是使用:

if(keyCode == KeyEvent.VK_???) 

现在您的代码是自我记录的。

答案 1 :(得分:0)

您想看看How to Write a Key ListenerKeyEvent对象有几种方法可以学习在生成事件时按下了什么修改键和鼠标按钮。