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

风格不统一 提交于 2019-12-11 16:49:06

问题


I'm using this for a simple 2.5D game but my keys don't seem to toggle. It isn't a problem while calling it in the main class as placing println statements in the if statements didn't run. 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);
        }
    }

}

回答1:


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.

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



来源:https://stackoverflow.com/questions/16802805/my-simple-key-listener-isnt-working-it-doesnt-seem-to-toggle-the-pressed-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!