如果您只想让进度条在一分钟内从零重复增加到满,并在每分钟结束时执行代码,您只需要:
ProgressBar progress = new ProgressBar();
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(progress.progressProperty(), 0)),
new KeyFrame(Duration.minutes(1), e-> {
// do anything you need here on completion...
System.out.println("Minute over");
}, new KeyValue(progress.progressProperty(), 1))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
这将为进度条创建一个“模拟”效果,即它不会每秒递增,而是在整分钟内平滑增加。
如果你真的想每秒递增,使用IntegerProperty来表示秒数,并绑定进度条的progress属性:
ProgressBar progress = new ProgressBar();
IntegerProperty seconds = new SimpleIntegerProperty();
progress.progressProperty().bind(seconds.divide(60.0));
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(seconds, 0)),
new KeyFrame(Duration.minutes(1), e-> {
// do anything you need here on completion...
System.out.println("Minute over");
}, new KeyValue(seconds, 60))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
这里的重点是 IntegerProperty 将在 0 到 60 之间进行插值,但只接受整数值(即,它将内插值截断为 int)。
这是第二版的 SSCCE:
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class OneMinuteTimer extends Application {
@Override
public void start(Stage primaryStage) {
ProgressBar progress = new ProgressBar();
progress.setMinWidth(200);
progress.setMaxWidth(Double.MAX_VALUE);
IntegerProperty seconds = new SimpleIntegerProperty();
progress.progressProperty().bind(seconds.divide(60.0));
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(seconds, 0)),
new KeyFrame(Duration.minutes(1), e-> {
// do anything you need here on completion...
System.out.println("Minute over");
}, new KeyValue(seconds, 60))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
StackPane root = new StackPane(progress);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}