javafx 实现倒计时功能
时间: 2023-09-06 11:10:10 浏览: 88
JavaFX 可以通过使用 `Timeline` 类来实现倒计时功能。下面是一个简单的倒计时示例:
```
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CountdownTimer extends Application {
private Timeline timeline;
private Label timerLabel = new Label();
private int timeSeconds = 10;
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.getChildren().add(timerLabel);
primaryStage.setScene(new Scene(root, 100, 50));
primaryStage.show();
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
// KeyFrame event handler
public void handle(ActionEvent event) {
timeSeconds--;
// update timerLabel
timerLabel.setText("Seconds Remaining: " + timeSeconds);
if (timeSeconds <= 0) {
timeline.stop();
}
}
}));
timeline.play();
}
public static void main(String[] args) {
launch(args);
}
}
```
在这个示例中,我们使用 `Timeline` 类来创建一个动画计时器,并将计时器的周期设置为 1 秒。在每个周期结束时,我们会更新 `timerLabel` 标签的文本,并检查是否到达了计时器的终点。
您可以根据需要调整 `timeSeconds` 变量的值,以设置不同的倒计时时间。