Java lwjgl keyboard handler

I created a class that accepts lwjgl keyboard input and turns it into a list of strings, which are all the keys that are currently pressed.

public class KeyHandler {

    ArrayList<String> keysPressed;

    public KeyHandler() {
        keysPressed = new ArrayList<String>();
    }

    public void checkKeys() {
        while (Keyboard.next()) {
            String keystring = Keyboard.getKeyName(Keyboard.getEventKey());
            if (!keysPressed.contains(keystring)) {
                keysPressed.add(keystring); // key has been pressed
            } else {
                keysPressed.remove(keystring); // key has been released
            }
        }
    }

    public void runKeys() {
    if (keysPressed.size() > 0) {
        for (String str : keysPressed) {
            System.out.println("Key handler got key:" + str);
            // run class for key
        }
    } else {
        // no keys have been pressed
    }
}

}

I am trying to find a way for "runKeys" to run a class with that name, for example.

W.java

public class W {

    public static void exc() {
        player.moveZ(10);
    }

}

The reason for this is to avoid having to run through 50+ if the instructions for checking input

+4
source share
1 answer
  • Create Map<Character, Consumer<Character>>.
  • Create a class for each character that implements the interface Consumer<Character>.
  • Store objects of these classes on the map.
  • , .

, .

+2

Source: https://habr.com/ru/post/1584692/


All Articles