JAVA FX-时间线动画(在动画过程中找到某些x,y点)

时间:2019-02-07 21:26:07

标签: java javafx

在此程序中,我试图在for循环中x == 600时使rect变为红色。基本上发生的是for循环的运行速度快于屏幕上的动画。矩形在实际上到达JavaFX屏幕中的特定点之前最终变成红色。

当它到达点x,y:(600,500)时,我想做的就是让蓝色矩形变成红色。

import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author Owner
 */
public class TestPoint extends Application {

    @Override
    public void start(Stage primaryStage) {

        Pane root = new Pane();
        Scene scene = new Scene(root, 1000, 1000);
        Rectangle rect = new Rectangle();
        Rectangle rectTwo = new Rectangle();

        //Obstacle that other square must hit
        rectTwo.setWidth(100);
        rectTwo.setHeight(100);
        rectTwo.setX(500);
        rectTwo.setY(500);
        rectTwo.setFill(Color.PINK);

        //for loop that causes the animation to properly move
        for (int x = 800; x >= 0; x--) {
            rect.setWidth(100);
            rect.setHeight(100);
            rect.setX(800);
            rect.setY(500);
            rect.setFill(Color.BLUE);
            Timeline timeline = new Timeline();
            timeline.setCycleCount(1);
            timeline.setAutoReverse(true);
            final KeyValue kv = new KeyValue(rect.xProperty(), x);
            final KeyFrame kf = new KeyFrame(Duration.seconds(8), kv);
            timeline.getKeyFrames().add(kf);
            timeline.play();
            //if it hits the point of rectTwo, change to Color.RED
            System.out.println(x);
            if (x == 600) {
                rect.setFill(Color.RED);
                break;//end 
            }
        }

        root.getChildren().addAll(rect, rectTwo);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

1 个答案:

答案 0 :(得分:3)

您误解了Timeline的工作方式。您的代码创建了201个Timeline动画,它们并行运行。在显示窗口之前 完成循环。以后,JavaFX会自动触发所有更新。

通过KeyFrame指定初始状态和目标状态就足够了。 KeyFrame可让您指定要在特定时间执行的处理程序;这可以用来改变颜色。另外,onFinished处理程序可用于为Rectangle着色。

rect.setWidth(100);
rect.setHeight(100);
rect.setY(500);
rect.setFill(Color.BLUE);

Timeline timeline = new Timeline(
        new KeyFrame(Duration.ZERO, new KeyValue(rect.xProperty(), 800)),
        new KeyFrame(Duration.seconds(8),
                evt -> rect.setFill(Color.RED),
                new KeyValue(rect.xProperty(), 600)));
timeline.play();