Handling Keyboard Sortcuts in JavaFx

DZone 's Guide to

Handling Keyboard Sortcuts in JavaFx

· Java Zone ·
Free Resource

A lot of times you need to to assign some functionality to some keyboard shortcut like F5 or Ctrl+R  in your application. JavaFx also provides KeyCodeCombination API for handling multiple key events.

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

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


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}