我正在使用javaFX并且目前仍然坚持这个:
Timeline timeline = new Timeline();
timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
System.out.println("Counting");
//myFunction(currentCycleStep) <------
}
}), new KeyFrame(Duration.seconds(SimulationController.speed)));
timeline.setCycleCount(5);
timeline.play();
我们不能将时间轴与for循环一起使用,但我们必须使用.setCycleCount()。那么我怎样才能得到计数的当前步骤?
答案 0 :(得分:0)
我认为没有直接的方法来从时间轴获得实际周期。
您可以为此编写自己的属性。 以下是一个示例,它监视currentTime并在每次更改&#34;方向&#34;时增加我们自己创建的属性的值。
示例:
<强>自动翻转=假强>
currentTime: 1s
currentTime: 2s
currentTime: 3s
currentTime: 0s <--------- increment actual cycle
currentTime: 1s
<强>自动翻转=真强>
currentTime: 1s
currentTime: 2s
currentTime: 3s
currentTime: 2s <--------- increment actual cycle
currentTime: 1s
我必须承认,这有点棘手,但也许这个解决方案已经满足您的需求。
代码示例:
(actualCycle从0开始,如果你希望它以1开头,只需将传递给SimpleIntegerProperty-Constructor的参数从0更改为1)
@Override
public void start(Stage primaryStage) throws Exception {
SimpleStringProperty testProperty = new SimpleStringProperty();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(1000), new KeyValue(testProperty, "1234")));
timeline.setCycleCount(Timeline.INDEFINITE);
// ----------------------------------------------------------------------
// we create our own property for the actual cycle-index
// ----------------------------------------------------------------------
SimpleIntegerProperty actualCycleProperty = new SimpleIntegerProperty(0);
timeline.currentTimeProperty().addListener((observable, oldValue, newValue) -> {
boolean smaller = newValue.toMillis() < oldValue.toMillis();
boolean evenCycleCount = actualCycleProperty.get() % 2 == 0;
if ((timeline.isAutoReverse() && !evenCycleCount && !smaller)
|| ((evenCycleCount || !timeline.isAutoReverse()) && smaller)) {
actualCycleProperty.set(actualCycleProperty.get() + 1);
}
});
actualCycleProperty.addListener((observable, oldValue, newValue) -> {
System.out.println(newValue);
});
timeline.play();
}