JavaFX Canvas Does Not Collect Key Events

I have the following code showing a JavaFX canvas with three consecutive welcome worlds

    StackPane root = new StackPane();

        Canvas canvas = new Canvas(250,250);
        canvas.setOnMouseEntered((a) -> System.out.println("hi"));
        canvas.setOnMousePressed((a) -> System.out.println("focus"));
        canvas.setOnKeyReleased(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
                System.out.println("Handled");
            }
        });
//        canvas.setOnKeyPressed((a) -> System.out.println("hi"));

        GraphicsContext context = canvas.getGraphicsContext2D();
        context.setFill(Color.BLUE);
        final int fontSize = 15, fontSpace = 5;
        context.setFont(Font.font(15));

        context.fillText("hello world", 75, 75);
        context.fillText("hello world", 75, 75 + fontSize + fontSpace);
        context.fillText("hello world", 75, 75 + (fontSize + fontSpace) * 2);

        root.getChildren().add(canvas);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();

When I click on it, it prints "hello." When I click on it, it prints "focus." When I press the keys, nothing happens. Is something missing?

+4
source share
2 answers

You need

canvas.setFocusTraversable(true);

as canvas there is no focusTraversabledefault.

+8
source

Add the following line:

canvas.addEventFilter(MouseEvent.ANY, (e) -> canvas.requestFocus());

After you click on your canvas, the canvas will ask for focus and recognize key events.

+7
source

Source: https://habr.com/ru/post/1543904/


All Articles