JavaFX Canvas not picking up key events


Question

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?

1
6
6/9/2014 6:47:47 PM

You need

canvas.setFocusTraversable(true);

as canvases do not have focusTraversable set by default.

12
6/9/2014 7:36:56 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon