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?
You need
canvas.setFocusTraversable(true);
as canvases do not have focusTraversable
set by default.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With