Skip to content

Keyboard listener

Pegacraffft edited this page Oct 28, 2020 · 1 revision

Keyboard listener

The keyboard listener is the listener, that helps you to interact with the scene via the keyboard. It is not needed to initialize this class. You can access it via the keyListener variable in the scene.

1. addListener(Integer keyCode, Predicate function)

addListener(Integer keyCode, Consumer function, boolean blocking)

This method is used to add a listener to the program. It executes a set of commands if a certain key is pressed.

Parameters:

Interger keyCode: The key you want to be pressed. (e. g. 'W' or 172).

Predicate<KeyEvent> function: The commands you want to execute. (e. g. e ->{System.out.println("Hello!")})

boolean blocking: If true: disables all processing of the key. If false: enables all processing of the key.

Example:

keyListener.addListener('W', e -> {
    System.out.println("Move up!");
});
keyListener.addListener('D', e -> {
    System.out.println("Move down!");
}, true);

2. isHeld(int key)

This method is used to check if a certain key is held down. It checks 60 times per second (if you didn't change it with Game.setFRameRate()). It is most commonly used to check for key presses in the logic loop. Returns true if the defined key is pressed. If not, it'll return false.

Parameters:

int key: The key you want to check for. (e. g. 'W' or 172)

Examples:

if(keyListener.isHeld('W')){
    System.out.println("Key 'W' is held down");
}

Public variables:

1. boolean[] pressesKeys

This variable is an array (new boolean[1024]) that contains all keys, that are currently pressed.