[英]JavaFX Key Pressed event for scene not executed if there is a focused component
我有一個代碼,當按下某個鍵時執行某些功能:
scene.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.F1) {
doSomething();
}
});
它可以工作,但只有在沒有聚焦組件的情況下,例如Button或TextField。 我注意到如果我按下CTRL + F1,或ALT + F1或SHIFT + F1,它會起作用,但只有F1才有效,如果沒有聚焦組件。 有辦法避免這種情況嗎?
-----更新-----正如@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();
}
}
});
每次按ESC鍵時,此代碼中的第12行打印兩次。 這意味着當我按下esc時,它會打開新窗口,當我關閉它時,窗口會再次打開。 我可以解決嗎?
請改用事件過濾器。 某些控件會消耗按鍵事件,因此使用事件過濾器可以在控件使用之前處理它們。
scene.addEventFilter(KeyEvent.KEY_PRESSED,
event -> System.out.println("Pressed: " + event.getCode()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.