Javafx keyboard shortcut key

I want to add a keyboard shortcut in javafx.

I have a scene and you want to implement a keyboard shortcut

my code is as follows

getApplication().getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {

        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.ESCAPE) {
                System.out.println("Key Pressed: " + ke.getCode());
            }
        }
    });
+4
source share
2 answers

Events move from the scene to the focused node (event capture), and then back to the scene (event bubble). An event filter is triggered during event capture, and onKeyPressed and an event handler are triggered during event bubbling. Some controls (e.g. TextField) consume the event, so it never returns to the scene, i.e. Event bubbling is canceled, and onKeyPressed for the scene does not work.

all, addEventFilter:

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());
            event.consume(); // <-- stops passing the event to next node
        }
    }
});

, KeyCodeCombination:

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);
            event.consume(); // <-- stops passing the event to next node
        }
    }
});

, (. [2]).

+6

, getApplication, , , KeyEventHandler Scene , .

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);
    }
}
+1

All Articles