如果有焦点组件,则不会执行场景的 JavaFX Key Pressed 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24125916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX Key Pressed event for scene not executed if there is a focused component
提问by Mateus Viccari
I have a code to execute some function when some key is pressed:
当按下某个键时,我有一个代码来执行某些功能:
scene.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.F1) {
doSomething();
}
});
And it works, but only if there is no focused components, like a Button or a TextField. I noticed it works if i press CTRL+F1, or ALT+F1, or SHIFT+F1, but only F1 just works if there is no focused component. Is there a way to avoid this?
它可以工作,但前提是没有焦点组件,例如 Button 或 TextField。我注意到如果我按 CTRL+F1、ALT+F1 或 SHIFT+F1,它会起作用,但如果没有聚焦组件,则只有 F1 才起作用。有没有办法避免这种情况?
-----UPDATE-----As @James_D said, i can do it using eventFilter instead of eventHandler:
-----更新-----正如@James_D 所说,我可以使用 eventFilter 而不是 eventHandler:
scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode().equals(KeyCode.ESCAPE)) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(TelaPrincipalController.class.getResource("/br/com/atualy/checkout/layout/telaoperacoescaixa.fxml"));
Parent parent = fxmlLoader.load();
Scene scene = new Scene(parent, 600,400);
Stage stage = new Stage();
stage.setScene(scene);
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(this.stage);
stage.showAndWait();
System.out.println("----> THIS IS BEING PRINTED TWICE ! <----");
} catch (IOException e) {
e.printStackTrace();
}
}
});
The line 12 in this code gets printed twice for every ESC key press. Which means that when i press esc, it opens the new window, and when i close it, the window opens one more time. Can i solve it?
每次按 ESC 键时,此代码中的第 12 行都会打印两次。这意味着当我按 esc 时,它会打开新窗口,而当我关闭它时,该窗口又会打开一次。我能解决吗?
采纳答案by James_D
Use an event filter instead. Some controls consume key press events, so using an event filter allows you to handle them before the control consumes them.
请改用事件过滤器。某些控件使用按键事件,因此使用事件过滤器可以让您在控件使用它们之前处理它们。
scene.addEventFilter(KeyEvent.KEY_PRESSED,
event -> System.out.println("Pressed: " + event.getCode()));