My simple key listener isn't working. It doesn

2019-08-16 09:43发布

问题:

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