Check a key's state without keyPressed/Released events

2.8k Views Asked by At

I need the check the state of a key (whether it's being pressed down or not) without using an event based method. Storing key states does not work; I need to check the real time state of the key. Anybody know how? Platform is JCreator v5.0 LE

1

There are 1 best solutions below

3
On

I don't see exactly the point, seeing how keyPressed(), keyReleased(), and keyTyped() are called whenever any key is pressed, without fail.

You also said that storing states is not working. Have you tried something like this?

boolean[] keys = new boolean[222]; // 222 is the highest keyCode value i know

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

// True is pressed, False is released
public boolean getState(int keyCode) {
  return keys[keyCode];
}

This is really the most reasonable way of checking the "real-time" state of a key. You can't just ask the computer for the state of a key without using a Listener. Perhaps some more information on what you need the "real-time" state for will get you a better answer.