在javaFX中通过KeyCombination触发事件 [英] Triggering an Event by KeyCombination in javaFX
问题描述
我正在尝试设置保存文件的快捷方式。
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();
}
}
});
然而,只需点击 S 键即可触发事件。有关原因的任何想法?
However, the event gets fired by just hitting the S key. Any ideas on why so?
推荐答案
KeyCodeCombination中所有修饰符的默认值
构造函数是 RELEASED
。因此,保存快捷方式与 S 键匹配, Shift 已发布, Alt 已发布, Meta 已发布,按下或释放控制(您指定的 ANY
值与按下或释放相匹配)。
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).
如果您希望这只匹配 Ctrl + S ,您应该使用
If you want this to only match Ctrl+S you should use
public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN);
更好的是
public static final KeyCombination saveShortcut = new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN);
这将匹配适合平台的快捷键(例如 Ctrl + Windows上的 S 和Mac上的 Cmd + S 。
which would match the shortcut key appropriate to the platform (e.g. Ctrl+S on windows and Cmd+S on Mac).
这篇关于在javaFX中通过KeyCombination触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!