Pages

Saturday, October 6, 2012

Handling Keyboard Sortcuts in JavaFx

A lot of times you need to to assign some functionality to some keyboard shortcut like F5 or Ctrl+R  in your application. It can be done as follows

[java]
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.F5) {
System.out.println("F5 pressed");
//Stop letting it do anything else
keyEvent.consume();
}
}
});
[/java]

JavaFx also provides KeyCodeCombination API for handling multiple key events.

[java]
final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.R,
KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (keyComb1.match(event)) {
System.out.println("Ctrl+R pressed");

}
}
});
[/java]