With the ScheduledExecutorService as far as I can tell, you cannot easily install it as deamon, and I do not want to play with stage.setOnCloseRequest(closeEvent -> {});
With AnimationTimer I cannot do something like Thread.sleep(100) between iterations, as you expected, because "AnimationTimer works in JavaFX stream".
ScheduledService is just hard for me to understand right now ...
so when I read and read about it, I came to the conclusion that perhaps this simple option would be better:
public class CountdownController implements Initializable{ @FXML private Label labTime; @FXML private Button buttSTOP; @Override public void initialize(URL location, ResourceBundle resources) { Timer timer = new Timer(true);
Thanks to James_D and ItachiUchiha . It works, let me know if I am missing something!
EDIT: I also include code for time tracking, as that was my original goal, maybe someone will find this useful as well:
public class CountdownController implements Initializable{ @FXML private Label labTime; @FXML private Button buttSTOP; private Timer timer = new Timer(true); //set it as a deamon private int iHours = 0, iMinutes = 1, iSeconds = 10; public void initCountdownController(int iHours, int iMinutes, int iSeconds){ this.iHours = iHours; this.iMinutes = iMinutes; this.iSeconds = iSeconds; } @Override public void initialize(URL location, ResourceBundle resources) { buttSTOP.setOnAction(e -> { buttSTOPAction(e); }); timer.schedule(new MyTimer(), 0, 1000); } private void buttSTOPAction(ActionEvent e) { timer.cancel(); } public class MyTimer extends TimerTask{ @Override public void run() { String time = iHours + ":" + iMinutes + ":" + iSeconds; Platform.runLater(() -> { labTime.setText(time); }); if(iSeconds < 1) if(iMinutes < 1) if(iHours < 1) this.cancel(); else{ iHours--; iMinutes = 59; iSeconds = 59; } else{ iMinutes--; iSeconds = 59; } else iSeconds--; } }
Tomasz
source share