Skip to content

Listening to Inputs from a Keyboard

Ralph Niemitz edited this page Mar 29, 2018 · 2 revisions

Works the same as listening to mice.

This library assumes that it deals with an english keyboard. So it will only be able to listen to standard keys. Some buttons may not work because of that.

Example for an implementation of KeyListener

public class Adapter implements KeyListener {

	@Override
	public void onKeyPress(KeyboardEvent event) {
	
		System.out.println("====");
		System.out.println("Code: " + event.getKeyCode());
		System.out.println("Name: " + event.getKeyName());
		System.out.println("====");
	}
	
	@Override
	public void onKeyRelease(KeyboardEvent event) {
	
		System.out.println("====");
		System.out.println("Code: " + event.getKeyCode());
		System.out.println("Name: " + event.getKeyName());
		System.out.println("====");
	}
}

Example for listening to all keyboards

DeviceManager.create();
DeviceManager.addKeyboardListener(new Adapter());
DeviceManager.getKeyboards().forEach(Keyboard::startListening);

// YOUR CODE

DeviceManager.destroy();

Example for listening to an individual keyboard

DeviceManager.create();
List<Keyboard> keyboard = DeviceManager.getKeyboards();
Keyboard myKeyboard = keyboards.get(0); // the first keyboard
myKeyboard.addKeyboardListener(new Adapter());
myKeyboard.startListening();

// When we listen to a single keyboard, we can ask which keys are currently down.
boolean isShiftDown = myKeyboard.isKeyDown(KeyboardEvent.KEY_SHIFT);

// YOUR CODE

DeviceManager.destroy();