2

For a game I am writing in java I need to open a dialogue when pressing the x key on my keyboard and then close it again when I press the x key again. The problem is whenever I press the x key its shows the dialogue on the screen for a millisecond then makes it disappear again. I think this is because it seems to think the key is being pressed multiple times instead of just once. Is there any way to make sure that I actually have to release the key before I can do the action bound to that same key again?

This is what I use to check for key presses:

public class KeyManager implements KeyListener {

    private boolean[] keys;
    public boolean up, down, left, right, enter, x, c;

    public KeyManager() {
        keys = new boolean[256];
    }

    public void tick() {
        up = keys[KeyEvent.VK_W];
        down = keys[KeyEvent.VK_S];
        left = keys[KeyEvent.VK_A];
        right = keys[KeyEvent.VK_D];
        enter = keys[KeyEvent.VK_ENTER];
        x = keys[KeyEvent.VK_X];
        c = keys[KeyEvent.VK_C];
    }

    @Override
    public void keyPressed(KeyEvent e) {
        keys[e.getKeyCode()] = true;
        // System.out.println("Pressed");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keys[e.getKeyCode()] = false;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}
Watermel0n
  • 241
  • 2
  • 10
Hanburger
  • 21
  • 1
  • 2
    in `keyPressed()` why don't you just put `if (!keys[e.getKeyCode()])` before performing the action and setting that boolean? ie. Only do the action if the key isn't currently being pressed – Mark Polivchuk Jul 07 '15 at 22:38

1 Answers1

0

Java Doesn't "check" if a key is pressed, it listens to key events.

Here is a documentation on how to write a key listener

if this is a swing application, KeyBindings is much better to use.

I think this is a duplicate question and your Question already has an answer here

Community
  • 1
  • 1
Kym NT
  • 670
  • 9
  • 28