我有以下代码显示带有3个连续hello世界的JavaFX Canvas
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();
当我将鼠标悬停在它上面时,它会打印“hi”。当我点击它时,它会打印“焦点”。当我按键时,没有任何反应。有什么我想念的吗?
答案 0 :(得分:11)
答案 1 :(得分:7)
添加以下行:
canvas.addEventFilter(MouseEvent.ANY, (e) -> canvas.requestFocus());
单击画布后,画布将请求焦点和识别键事件。