我有一个带有“animation()”方法的类,该方法使用 JavaFX KeyFrame 和 Timeline 类。当我尝试执行对象a1(a1.animation())的这个方法时,对象a2(a2.animation)的方法也会被调用,并且两者并行执行。我应该做哪些修改才能使方法的执行是线性的,即执行对象a1的方法,最后开始执行对象a2的方法?
我已经尝试过使用setOnFinished()方法,但是只执行了a1对象方法,没有执行a2对象方法。
public class Example{
//method
public void animation(){
Timeline timeline = new Timeline();
KeyFrame keyFrame = new KeyFrame(Duration.millis(10), event -> {
/*
code here
*/
});
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
}
//call method on start
@Override
public void start(Stage primaryStage) throws IOException{
Example a1 = new Example();
Example a2 = new Example();
a1.animation();
a2.animation();
}
重构您的方法,使其仅返回动画,而不是播放它:
public class Example{
//method
public Animation animation(){
Timeline timeline = new Timeline();
KeyFrame keyFrame = new KeyFrame(Duration.millis(10), event -> {
/*
code here
*/
});
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
// timeline.play();
return timeline;
}
}
然后将两者放入
SequentialTransition
:
@Override
public void start(Stage primaryStage) throws IOException{
Example a1 = new Example();
Example a2 = new Example();
SequentialTransition sequential = new SequentialTransition(
a1.animation(),
a2.animation()
);
sequential.play();
}