子节点上的EventHandler

时间:2018-06-07 21:23:24

标签: java javafx

所以我在Circle上加了EventHandler。当我运行它并按键时没有任何反应。

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {

        Group root = new Group();
        Scene scene = new Scene(root, 600, 400);
        Circle circle = new Circle(300,200,10);

        circle.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                System.out.println("Hello!");
            }
        });

        root.getChildren().add(circle);
        stage.setScene(scene);
        stage.show();
    }
}

我认为这是因为事件没有一直传递到Circle。有没有办法做到这一点,或者我应该将EventHandler放在Scene上呢?

0 个答案:

没有答案