JavaFX: How to handle keystroke combinations without a menu/menubar

I don’t know if there’s a better way to do this, but I can confirm that this code works as a way to handle/capture keystroke combinations in JavaFX without having to use a menu/menubar:

scene.setOnKeyPressed((keyEvent: KeyEvent) => {
    if (keyEvent.getCode == KeyCode.F5) {
        System.out.println("F5 pressed")
        //Stop letting it do anything else
        keyEvent.consume()
    }
})

val keyComb1: KeyCombination  = new KeyCodeCombination(
    KeyCode.F,
    KeyCombination.META_DOWN
)

scene.addEventHandler(KeyEvent.KEY_RELEASED, (event: KeyEvent) => {
    if (keyComb1.`match`(event)) {
        System.out.println("CMD-F pressed")
    }
})

I found the Java version of that code at this DZone page. The best part of this code is that it shows how to capture keystrokes in JavaFX without having to use a menu. Because I don’t want a JavaFX-style menu, this is a good thing. My code also shows the “lambda” syntax, which is easier to read than the old-school approach.

Update: See the Comments section below for another approach that is more direct.

Permalink

Why don't you use Accelerators registered on the scene?


Scene scene = new Scene();
scene.getAccelerators().put(
new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN),
new Runnable() {
@Override public void run() {
System.out.println("Key pressed")
}
}
);

Note: Using SHORTCUT_DOWN is platform independent and will be resolved to CMD_DOWN under Mac OS X and CONTROL_DOWN under Windows.