简体   繁体   English

我简单的按键侦听器无法正常工作。 似乎没有切换按下的布尔值。 (Java)

[英]My simple key listener isn't working. It doesn't seem to toggle the pressed boolean. (Java)

I'm using this for a simple 2.5D game but my keys don't seem to toggle. 我将其用于简单的2.5D游戏,但是我的按键似乎没有切换。 It isn't a problem while calling it in the main class as placing println statements in the if statements didn't run. 在主类中调用它不是问题,因为将println语句放置在if语句未运行的情况下。 Thanks ahead of time. 提前谢谢。

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class InputHandler implements KeyListener {

    public InputHandler(Game game) {
        game.addKeyListener(this);
    }

    public class Key {
        private boolean pressed = false;
        private int numTimesPressed = 0;

        public boolean isPressed() {
            return pressed;
        }

        public int getnumTimesPressed() {
            return numTimesPressed;
        }

        public void toggle(boolean isPressed) {
            pressed = isPressed;
            if (isPressed()) {
                numTimesPressed++;
            }
        }

    }

    // *This is where your keys go.

    public Key up = new Key();
    public Key down = new Key();
    public Key left = new Key();
    public Key right = new Key();

    public void keyPressed(KeyEvent e) {
        toggleKey(e.getKeyCode(), true);

    }

    public void keyReleased(KeyEvent e) {
        toggleKey(e.getKeyCode(), false);

    }

    public void keyTyped(KeyEvent e) {
    }

    public void toggleKey(int keyCode, boolean isPressed) {
        if (keyCode == KeyEvent.VK_W) {
            up.toggle(isPressed);
        }
        if (keyCode == KeyEvent.VK_S) {
            down.toggle(isPressed);
        }
        if (keyCode == KeyEvent.VK_A) {
            left.toggle(isPressed);
        }
        if (keyCode == KeyEvent.VK_D) {
            right.toggle(isPressed);
        }
    }

}

The problem with KeyListener is that it will only notify you of key events when the component it is registered to is focusable and has focus. KeyListener的问题在于,仅当将其注册到的组件具有焦点并具有焦点时,它才会将关键事件通知您。

Many containers are not focusable by default. 默认情况下,许多容器无法聚焦。

You are actually better of using Key Bindings 实际上,您最好使用键绑定

You could take a look at I am trying to make ball gradually move for an example 您可以看一下我正在尝试使球逐渐移动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM