在这个程序中,我试图在 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);
}
}
最佳答案
您误解了 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();
关于JAVAFX - 时间线动画(在动画过程中找到某些x,y点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582556/