JavaFX Live Time and Date
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 -> {
LocalTime currentTime = LocalTime.now();
time.setText(currentTime.getHour() + ":" + currentTime.getMinute() + ":" + currentTime.getSecond());
}),
new KeyFrame(Duration.seconds(1))
);
clock.setCycleCount(Animation.INDEFINITE);
clock.play();
}
The @Shekhar Rai answer works well, but here is a shorter version who works pretty well too.
@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();
}
The main advantage is that you dont have to define every variables (seconds, minutes, ...)