This is a very basic keyboard handler class that you can use to listen for multiple key presses. It will respond to the first 128 key codes as defined in the KeyEvent class. If you need to respond to codes above this range, just increase the array size accordingly. You can see all of the codes here:
http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.awt.event.KeyEvent.CHAR_UNDEFINEDAnd now for Keyboard.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;
public class Keyboard {
private static boolean[] pressed = new boolean[128];
public static boolean isPressed(int key) { return pressed[key]; } public static KeyListener listener = new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code < pressed.length) { pressed[code] = true; } }
@Override public void keyReleased(KeyEvent e) { int code = e.getKeyCode(); if (code < pressed.length) { pressed[code] = false; } } }; } |
The class defines a static member which is the listener, and can be added to your JPanel (or Applet) as follows:
1
| panel.addKeyListener(KeyBoard.listener); |
Checking if a key has been pressed in your thread is as easy as:
1 2 3 4 5 6
| if (Keyboard.isKeyPressed(KeyEvent.VK_LEFT)) { ... } if (Keyboard.isKeyPressed(KeyEvent.VK_DOWN)) { ... } |
One known limitation of this code is that if a key is pressed and released before your main game loop thread has a chance to read its state, then it will be missed. I have a solution to this, but have edited it out just to make the example a lot simpler to follow. It isn't such a big deal.[/code][/code]