IT干货网

java之JavaFX实时时间和日期

bhlsheji 2025年12月25日 编程设计 102 0

我目前正在使用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(); 
} 

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> 

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(); 
   } 
} 

如您所见,我对其进行了测试,可以在控制台中打印实时时间。是的,它起作用了,但是标签仍然是静态的。

请您参考如下方法:

我认为您需要为此使用FX UI线程Platform.runLater(...),但是您可以在 Controller 类中使用 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(); 
} 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!