Over a million developers have joined DZone.
Silver Partner

Handling Keyboard Sortcuts in JavaFx

· Java Zone

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

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
    keyEvent.consume();
   }
 }
});


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

                    }
                }
            });

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

Topics:
javafx

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

{{ parent.tldr }}

{{ parent.urlSource.name }}