JavaFX实时时间和日期 [英] JavaFX Live Time and Date
问题描述
我正在构建一个使用JavaFx的应用程序,它具有一个额外的功能,可以在场景的顶角显示当前的日期和时间。由于我是JavaFX的新手,我不知道如何实现这个。
I am building currently an application using JavaFx with an extra feature that displays the current date and time in the top corner of the scene. Since I am new to JavaFX, I don't know how to implement this one.
我试图在swing中使用旧代码但是我遇到了IllegalStateException错误。
I tried to use an old code in swing but I got an IllegalStateException Error.
这是我的代码。
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();
}
}
如你所知,我测试了它打印的实时时间在控制台中。是的,它有效,但标签仍然是静态的。
As you notice, I tested it printing the live time in the console. Yeah it worked, but the label is still static.
推荐答案
我认为你需要FX UI线程 Platform.runLater(...)
为此,你可以使用 时间轴
,
I think you need FX UI Thread Platform.runLater(...)
for that, but you can do something like this using Timeline
in you controller class,
@FXML
public void initialize() {
Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
second = LocalDateTime.now().getSecond();
minute = LocalDateTime.now().getMinute();
hour = LocalDateTime.now().getHour();
time.setText(hour + ":" + (minute) + ":" + second);
}),
new KeyFrame(Duration.seconds(1))
);
clock.setCycleCount(Animation.INDEFINITE);
clock.play();
}
这篇关于JavaFX实时时间和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!