[英]JavaFX Canvas not picking up key events
我有以下代碼顯示具有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”。 當我單擊它時,它會打印“焦點”。 當我按下鍵時,什么也沒發生。 有什么我想念的嗎?
添加以下行:
canvas.addEventFilter(MouseEvent.ANY, (e) -> canvas.requestFocus());
單擊畫布后,畫布將請求焦點並識別關鍵事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.