JavaFX实时时间和日期

Bry*_*yes 4 java javafx javafx-8

我正在构建一个使用JavaFx的应用程序,它具有一个额外的功能,可以在场景的顶角显示当前的日期和时间.由于我是JavaFX的新手,我不知道如何实现这个.

我尝试在swing中使用旧代码但是我遇到了IllegalStateException错误.

这是我的代码.

MainMenuController.java

@FXML private Label time;

private int minute;
private int hour;
private int second;

@FXML
public void initialize() {

    Thread clock = new Thread() {
        public void run() {
            for (;;) {
                DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
                Calendar cal = Calendar.getInstance();

                second = cal.get(Calendar.SECOND);
                minute = cal.get(Calendar.MINUTE);
                hour = cal.get(Calendar.HOUR);
                //System.out.println(hour + ":" + (minute) + ":" + second);
                time.setText(hour + ":" + (minute) + ":" + second);

                try {
                    sleep(1000);
                } catch (InterruptedException ex) {
                     //...
                }
            }
        }
    };
    clock.start();
}
Run Code Online (Sandbox Code Playgroud)

MainMenu.fxml

 <children>
   <Label fx:id="time" textFill="WHITE">
     <font>
       <Font name="Segoe UI Black" size="27.0" />
     </font>
   </Label>
   <Label fx:id="date" textFill="WHITE">
     <font>
       <Font name="Segoe UI Semibold" size="19.0" />
     </font>
   </Label>
 </children>
Run Code Online (Sandbox Code Playgroud)

Main.java

public class Main extends Application {

   public static void main(String[] args) {
       launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception {
       Parent root = FXMLLoader.load(getClass().getResource("view/MainMenu.fxml"));
       primaryStage.setScene(new Scene(root,1366, 768));
       primaryStage.show();
   }
}
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,我测试了它在控制台中打印实时时间.是的,它有效,但标签仍然是静态的.

She*_*Rai 11

我认为你需要FX UI Thread Platform.runLater(...),但你可以Timeline在你的控制器类中使用这样的东西,

@FXML
public void initialize() {

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {        
        LocalTime currentTime = LocalTime.now();
        time.setText(currentTime.getHour() + ":" + currentTime.getMinute() + ":" + currentTime.getSecond());
    }),
         new KeyFrame(Duration.seconds(1))
    );
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,每秒更新一次的时间线可能比实时时间晚一秒.使用`AnimationTimer`将与UI渲染允许的一样准确.使用`LocalTime`和`DateTimeFormatter`而不是遗留的`Calendar`类可能也更清晰. (2认同)

小智 7

@Shekhar Rai的答案很好用,但是这里的简短版本也很好用。

@FXML
Label dateTime;

@Override
public void initialize(URL location, ResourceBundle resources) {
    initClock();
}

private void initClock() {

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        dateTime.setText(LocalDateTime.now().format(formatter));
    }), new KeyFrame(Duration.seconds(1)));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}
Run Code Online (Sandbox Code Playgroud)

主要优点是您不必定义每个变量(秒,分钟,...)