Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Karel KeyListener
//Add these lines to the top of your main method to make the key listener work
//implement the variable listener however you want, this anonymous one is just a sample
KeyListener listener = new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
//using e.getChar() is not always a reliable way to find out what key is pressed
//I think you're supposed to use e.getKeyCode which will return an int representing a VK_ (virtual key) value
System.out.println("pressed " + e.getKeyChar());
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("released " + e.getKeyChar());
}
@Override
public void keyTyped(KeyEvent e) {
System.out.println("typed " + e.getKeyChar());
}
};
//this class tells the JVM to also send key events to the listener above.
//it's ugly, but the only way to hide it is add it to a library. It is static though.
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
listener.keyPressed(e);
break;
case KeyEvent.KEY_RELEASED:
listener.keyReleased(e);
break;
case KeyEvent.KEY_TYPED:
listener.keyTyped(e);
break;
}
//must return false to ensure the other KeyEventDispatchers work as intended.
return false;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment