javafx keyboard event shortcut key

倖福魔咒の 提交于 2019-12-03 14:20:19
user2229691

Events travel from the scene to the focused node (event capturing) and then back to the scene (event bubbling). Event filter are triggered during event capturing, while onKeyPressed and event handler are triggered during event bubbling. Some controls (for example TextField) consume the event, so it never comes back to the scene, i.e. event bubbling is canceled and onKeyPressed for the scene doesn't work.

To get all key pressed events use addEventFilter method:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.ESCAPE) {
            System.out.println("Key Pressed: " + ke.getCode());
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

If you want to capture key combinations use the KeyCodeCombination class:

scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    final KeyCombination keyComb = new KeyCodeCombination(KeyCode.ESCAPE,
                                                          KeyCombination.CONTROL_DOWN);
    public void handle(KeyEvent ke) {
        if (keyComb.match(ke)) {
            System.out.println("Key Pressed: " + keyComb);
            ke.consume(); // <-- stops passing the event to next node
        }
    }
});

There is also the possibility to add shortcuts to the menu by setting an accelerator (see [2]).

References

I am not sure what you are doing with getApplication, but just to show that KeyEventHandler on Scene works, here's a demo for you.

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MyApp extends Application {
    public void start(Stage stage) {

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        Label heading = new Label("Press Key");
        Label keyPressed = new Label();
        root.getChildren().addAll(heading, keyPressed);
        Scene scene = new Scene(root, 400, 300);

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                keyPressed.setText("Key Pressed: " + ke.getCode());
            }
        });

        stage.setTitle("My JavaFX Application");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!