Java keyReleased工作正常,但keyPressed丢失控制

时间:2016-10-09 05:12:29

标签: java keylistener

我最近正在制作游戏,但我遇到了一个问题。当我按下WASD键时,有时没有响应,但是当我按下左箭头键或右箭头键时,它运行良好。此外,我尝试在KeyPressed和keyReleased中使用System.out.println()进行调试,我注意到当没有响应时,keyPressed中没有打印的``消息,但是在keyReleased中。这个问题让我很困惑。

我使用JFrame进行游戏,我只将Canvas添加到JFrame中。我为JFrame和Canvas添加了keyListener(我试图删除其中一个和requestFocus,但问题仍未解决)。

这是一段代码。
对于keyPressed:

@Override
public void keyPressed(KeyEvent e) {
    //When keyPressed lost control, this line did not even work
    System.out.println("key pressed");
    if(e.getKeyCode() == KeyEvent.VK_A){
        left = true;
    }
    else if(e.getKeyCode() == KeyEvent.VK_D){
        right = true;
    }
    else if(e.getKeyCode() == KeyEvent.VK_SPACE){
        jump();
    }
    else if(e.getKeyCode() == KeyEvent.VK_LEFT){
        attackLeft = true;
    }
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        attackRight = true;
    }
    else if(e.getKeyCode() == KeyEvent.VK_R) init();
    else if(e.getKeyCode() == KeyEvent.VK_Q) System.exit(0);
}

对于keyReleased:

@Override
public void keyReleased(KeyEvent e) {
    //This line will output the message every time I released even
    //if keyPressed did not work.
    System.out.println("Key released");
    if(e.getKeyCode() == KeyEvent.VK_A) left = false;
    else if(e.getKeyCode() == KeyEvent.VK_D) right = false;
    else if(e.getKeyCode() == KeyEvent.VK_LEFT) attackLeft = false;
    else if(e.getKeyCode() == KeyEvent.VK_RIGHT) attackRight = false;
}

keyPressed无效时的示例输出:

Key pressed
Key released
Key pressed
Key released
Key released
Key released
Key released
Key released
Key released
Key released
Key released
Key released

1 个答案:

答案 0 :(得分:0)

您可能更喜欢从Canvas切换到JPanel并正确使用面板的getActionMap()。put(...)和getInputMap()。put(...)(并覆盖paintComponent方法)

您还应该查看here

一个简单的例子可能看起来像这样

public class Example2 extends JPanel {

    public Example2() {
        super(new BorderLayout());

        JPanel canvas = new JPanel();

        Action action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getActionCommand());
            }
        };

        InputMap im = canvas.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

        im.put(KeyStroke.getKeyStroke('w'), "wasd");
        im.put(KeyStroke.getKeyStroke('a'), "wasd");
        im.put(KeyStroke.getKeyStroke('s'), "wasd");
        im.put(KeyStroke.getKeyStroke('d'), "wasd");

        canvas.getActionMap().put("wasd", action);

        add(canvas, BorderLayout.CENTER);

    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setContentPane(new Example2());
        frame.setSize(200, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}