如果存在焦点组件,则不执行场景的JavaFX Key Pressed事件 [英] JavaFX Key Pressed event for scene not executed if there is a focused component

查看:491
本文介绍了如果存在焦点组件,则不执行场景的JavaFX Key Pressed事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码在按下某个键时执行某些功能:

I have a code to execute some function when some key is pressed:

scene.setOnKeyPressed(event -> {
    if (event.getCode() == KeyCode.F1) {
        doSomething();
    }
});

并且它有效,但前提是没有焦点组件,如Button或TextField。
我注意到如果按CTRL + F1,或ALT + F1或SHIFT + F1,它会起作用,但只有F1才有效,如果没有聚焦组件。
有没有办法避免这种情况?

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?

-----更新-----
As @James_D说,我可以使用eventFilter代替eventHandler:

-----UPDATE----- As @James_D said, i can do it using eventFilter instead of 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时,它会打开新窗口,当我关闭它时,窗口会再次打开。
我能解决吗?

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?

推荐答案

请改用事件过滤器。有些控件会消耗按键事件,因此使用事件过滤器可以在控件使用它们之前处理它们。

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()));

这篇关于如果存在焦点组件,则不执行场景的JavaFX Key Pressed事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆