Skip to content

Instantly share code, notes, and snippets.

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() {
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());
public void keyReleased(KeyEvent e) {
System.out.println("released " + e.getKeyChar());
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.
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
case KeyEvent.KEY_TYPED:
//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