Here's random parts of an InputManager class I made.
First you need to find the keyboard and store it for future use.
1 2 3 4 5 6 7
| private static Keyboard findKeyboard() { for (int i = 0; i < controllers.length; i++) if (controllers[i].getType() == Controller.Type.KEYBOARD) return (Keyboard)controllers[i]; return null; } |
In an initializer somewhere...
1
| keyboard = findKeyboard(); |
Then every timestep you want to poll the keyboard. This simply goes through all the buttons to find what has been pressed, putting it all in a giant boolean list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public static boolean[] pollKeyboard() { keyboard.poll(); Component[] c = keyboard.getComponents(); boolean[] b = new boolean[c.length]; for (int i = 0; i < c.length; i++) { if (c[i].getPollData() != 0) b[i] = true; else b[i] = false; } return b; } |
To use the above, you'd do this:
1 2 3 4
| if (pollKeyboard()[net.java.games.input.Component.Identifier.Key.A]) { doA(); } |
Or if you just want to avoid a boolean list (better depending on what you want to do) you can do this:
1 2 3 4
| if ((keyboard.isKeyDown(net.java.games.input.Component.Identifier.Key.A)) { doA(); } |