简体   繁体   中英

Java lwjgl keyboard handler

I've created a class that takes lwjgl's keyboard input and turns it into a list of strings that are all the keys that are currently being 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'm trying to figure out a way so that 'runKeys' will run a class with that name, for example.

W.java

public class W {

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

}

The reason for doing this is to avoid having to run through 50+ if statements to check for input

  • Create a Map<Character, Consumer<Character>> .
  • Create a class for each character which implements Consumer<Character> interface.
  • Store objects of those classes in the map.
  • Call consume on the appropriate consumer object from the map using your detected keystroke character.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM