按住并离开Java的键侦听器时,空格键不注册

时间:2019-05-21 18:03:58

标签: java keylistener keyevent

当我举起手离开时,程序会很好地注册它们。但是,当我碰到空格时它不会注册。如果您将VK_LEFT切换为VK_RIGHT,则在按住空格的同时继续向右和向上滑动即可。

import javax.swing.JFrame;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class Testing implements KeyListener {

    public boolean isUp;
    public boolean isLeft;

    public Testing() {
        JFrame application = new JFrame();

        application.addKeyListener(this);
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(500, 500); 
        application.setVisible(true);
    }

    public static void main(String[] args) {
        Testing test = new Testing();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_UP)
            isUp = true;
        else if(e.getKeyCode() == KeyEvent.VK_LEFT)
            isLeft = true;
        else if(isUp && isLeft && e.getKeyCode() == KeyEvent.VK_SPACE)
            System.out.println("pew pew");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_UP)
            isUp = false;
        else if(e.getKeyCode() == KeyEvent.VK_LEFT)
            isLeft = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}

它应该在向上和向左移动时记录空间,就像向上和向右移动一样

0 个答案:

没有答案