Last active
June 6, 2017 16:45
-
-
Save ebanisadr/280f22cb6e8d5e370d7157092112cf9f to your computer and use it in GitHub Desktop.
Karel KeyListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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