如何在JavaFx中更改其方向时触发事件

时间:2017-12-15 09:41:08

标签: java animation javafx-8

我想使用PathTransition

为节点设置动画

在此示例中,节点是标签:

Label l1 = new Label("Hello");
Path path = new Path();
MoveTo p1 = new MoveTo(0,0);
LineTo p2 = new LineTo(100,100);
LineTo p3 = new LineTo(100,0);
path.getElements().addAll(p1,p2,p3);

PathTransition pathTransition = new PathTransition();
pathTransition.setDuration(Duration.millis(1000));
pathTransition.setPath(path);
pathTransition.setNode(l1);

pathTransition.play();

我想要的是触发 运动方向改变时的事件(例如,当标签开始从p2移动到p3时)

有没有解决方案?

1 个答案:

答案 0 :(得分:0)

为每个部分创建一个单独的PathTransition,并为每个部分注册一个onFinished处理程序。然后将所有转换放在SequentialTransition

import javafx.animation.PathTransition;
import javafx.animation.SequentialTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;

public class SequentialTransitionExample extends Application {

    @Override
    public void start(Stage primaryStage) {

        Label label = new Label("Hello");

        int totalAnimationTime = 2000 ; // millis
        double[] points = {0,0, 100, 100, 100, 0} ;

        SequentialTransition animation = new SequentialTransition();
        int numPaths = points.length / 2 - 1 ;
        int time = totalAnimationTime / numPaths ;
        for (int i = 2 ; i < points.length - 1; i += 2) {
            MoveTo moveTo = new MoveTo(points[i-2], points[i-1]);
            LineTo lineTo = new LineTo(points[i], points[i+1]);
            Path path = new Path(moveTo, lineTo);
            PathTransition pathTransition = new PathTransition(Duration.millis(time), path, label);

            int p = i / 2 ;
            pathTransition.setOnFinished(e -> System.out.println("Reached point "+p));

            animation.getChildren().add(pathTransition);
        }

        StackPane root = new StackPane(label);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();

        animation.play();
    }

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