Arhowk
Arhowk

Reputation: 931

JavaFX Canvas not picking up key events

I have the following code showing a JavaFX Canvas with 3 consecutive hello 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 mouse over it, it prints "hi". When I click it, it prints "focus". When i press keys, nothing happens. Is there something I'm missing?

Upvotes: 8

Views: 6432

Answers (2)

Markus
Markus

Reputation: 1482

Add the following line:

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

After you click your canvas, the canvas will request the focus and recognice key events.

Upvotes: 8

James_D
James_D

Reputation: 209623

You need

canvas.setFocusTraversable(true);

as canvases do not have focusTraversable set by default.

Upvotes: 17

Related Questions