如何在按住 KeyEvent 时只触发一次?

How do I the KeyEvent only once when it is held down?

我正在尝试以一定的速度发射导弹,但目前您只需按住开火按钮 (Space),它就会连续发射导弹。

我相信这是因为 KeyEvent 在你按住它时被触发,而我需要它做的只是在你按住它时触发一次。

我怎样才能让它检测到按下按钮只按下一次?

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_SPACE) {
        fire();
    }

    if (key == KeyEvent.VK_A) {
        dx = -1;
    }

    if (key == KeyEvent.VK_D) {
        dx = 1;
    }
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_SPACE) {

    }
    if (key == KeyEvent.VK_A) {
        dx = 0;
    }

    if (key == KeyEvent.VK_D) {
        dx = 0;
    }
}

只需添加一个检查以确保您在允许自己再次开火之前已释放钥匙。我使用 AtomicBoolean 来确保触发不同事件不会造成多线程问题。

private final AtomicBoolean canShoot = new AtomicBoolean(true);

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    if (key == KeyEvent.VK_SPACE) {
        if (canShoot.compareAndSet(true, false)) {
            fire();
        }
    }
    // snip
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();

    if (key == KeyEvent.VK_SPACE) {
        canShoot.set(true);
    }
    // snip
}