Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Arhowk Avatar asked Jun 09 '14 18:06

Arhowk


2 Answers

You need

canvas.setFocusTraversable(true);

as canvases do not have focusTraversable set by default.

like image 194
James_D Avatar answered Oct 29 '22 11:10

James_D


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.

like image 7
Markus Avatar answered Oct 29 '22 11:10

Markus