Triggering an Event by KeyCombination in javaFX

坚强是说给别人听的谎言 提交于 2019-12-22 10:35:34

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/22751657/triggering-an-event-by-keycombination-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!