在转换期间检测对象是否在窗格上方

时间:2015-01-03 13:34:18

标签: animation javafx-2

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

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结束时,它会检测到它?

1 个答案:

答案 0 :(得分:1)

尝试

    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 8之前版本)Java版本,则需要将panerect声明为final