在过渡期间检测对象是否在窗格上方

Detect if object is over pane during transition

我正在尝试检测我使用 PathTransition 移动的元素是否正在进入窗格的 space。 这是我的代码:

public class Demo extends Application {

    private void init(Stage primaryStage) {     
        Group root = new Group();
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 800, 600));

        Rectangle rect = new Rectangle(5, 5, Color.BLACK);
        root.getChildren().add(rect);

        Path path = new Path();
        path.getElements().add (new MoveTo (0, 350));
        path.getElements().add (new LineTo(400, 350));

        PathTransition pathTransition = new PathTransition();
        pathTransition.setDuration(Duration.millis(5000));
        pathTransition.setPath(path);
        pathTransition.setNode(rect);
        pathTransition.setAutoReverse(false);

        AnchorPane pane = new AnchorPane();
        pane.setPrefSize(250, 200);
        pane.relocate(300, 300);
        pane.setStyle("-fx-border-color: #000000;");
        root.getChildren().add(pane);

        pathTransition.play();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }

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

有没有办法将事件绑定到 pane 对象,当 rect 过去时,它会检测到它?

尝试

    BooleanBinding intersects = new BooleanBinding() {

        {
            this.bind(pane.boundsInParentProperty(), rect.boundsInParentProperty());
        }

        @Override
        protected boolean computeValue() {
            return pane.getBoundsInParent().intersects(rect.getBoundsInParent());
        }

    };

    intersects.addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable,
                Boolean oldValue, Boolean newValue) {
            if (newValue) {
                System.out.println("Intersecting");
            } else {
                System.out.println("Not intersecting");
            }
        }

    });

如果您仍在使用 Java 的旧版本(Java 8 之前),您需要将 panerect 声明为 final.