Reputation: 145
I'm using javaFX and currently stuck at this:
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();
As we can't use the timeline with for loop, but we have to use .setCycleCount(). So how can I get the current step of the count?
Upvotes: 0
Views: 1704
Reputation: 221
I think there is no direct way to get the actual cycle from a Timeline.
You could write your own Property for this. The following is an example, which watches the currentTime and increments the value of our self created property everytime it changes "direction".
Example:
autoReverse=false
currentTime: 1s
currentTime: 2s
currentTime: 3s
currentTime: 0s <--------- increment actual cycle
currentTime: 1s
autoReverse=true
currentTime: 1s
currentTime: 2s
currentTime: 3s
currentTime: 2s <--------- increment actual cycle
currentTime: 1s
I must admit, that this is a bit tricky, but maybe this solution already fits your needs.
Code-Example:
(actualCycle starts with 0, if you want it to start with 1, just change the param you pass to the SimpleIntegerProperty-Constructor from 0 to 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();
}
Upvotes: 0