📜  javafx 实时日期和时间 - Java (1)

📅  最后修改于: 2023-12-03 15:31:36.141000             🧑  作者: Mango

JavaFX 实时日期和时间

JavaFX 提供了一种简单的方法来显示实时日期和时间。可以使用 javafx.scene.control.Labeljava.time.LocalDateTime 类来实现它。

步骤
  1. 导入类
import javafx.scene.control.Label;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
  1. 创建一个 Label
Label label = new Label();
  1. 创建一个 DateTimeFormatter 对象,并定义日期时间格式。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  1. start 方法中创建一个 Timeline 对象,设置其循环周期,挂起时间和事件处理程序。
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
    LocalDateTime now = LocalDateTime.now();
    label.setText(formatter.format(now));
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

完整代码如下:

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeExample extends Application {
    @Override
    public void start(Stage stage) {
        Label label = new Label();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
            LocalDateTime now = LocalDateTime.now();
            label.setText(formatter.format(now));
        }));

        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();

        Scene scene = new Scene(label);
        stage.setScene(scene);
        stage.setTitle("实时日期和时间");
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
解释
  1. 我们使用 LocalDateTime.now() 方法获取当前日期和时间。这个方法返回一个 LocalDateTime 对象。
  2. 使用 DateTimeFormatter 类将日期和时间格式化为字符串。
  3. Timeline 对象创建一个时间轴动画。在每个循环中,事件处理程序设置 Label 的文本为当前日期和时间。Timeline 对象在导航栏上显示动画持续时间。
  4. Animation.INDEFINITE 使动画永无止境。

参考文献:

  1. https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html
  2. https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
  3. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
  4. https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html