Question

I am trying to set a shortcut to save a file.

public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_ANY);

I trigger an action by:

sceneRoot.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (saveShortcut.match(event)) {
                saveProject.fire();
            } 
        }

    });

However, the event gets fired by just hitting the S key. Any ideas on why so?

Was it helpful?

Solution

The default value for all the modifiers in the KeyCodeCombination constructor is RELEASED. So your save shortcut matches the key S with Shift released, Alt released, Meta released, and Control either pressed or released (the ANY value that you specified matches either pressed or released).

If you want this to only match Ctrl+S you should use

public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN);

Better still is

public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN);

which would match the shortcut key appropriate to the platform (e.g. Ctrl+S on windows and Cmd+S on Mac).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top