The Timer class
public class LureTimer{
private int totalTime = 0;
private int minutes = 0;
private static Timer mTimer;
private boolean timeRunning;
private static LureUI mLureUI;
private StringProperty theTime = new SimpleStringProperty(this, "theTime", "Test");
public void startTimer(){
System.out.println("Started");
mTimer = new Timer();
mLureUI = new LureUI();
theTimer();
timerStarted();
}
public void theTimer() {
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if (totalTime != 59) {
totalTime++;
timePrint();
} else {
totalTime = 0;
minutes++;
timePrint();
}
checkTime();
}
}, 0, 1000);
}
private void checkTime() {
if(minutes == 30){
stopTimer();
}
}
public void timePrint(){
if (totalTime < 10 && minutes < 10) {
System.out.println("0" + minutes + ":0" + totalTime);
setTheTime("0" + minutes + ":0" + totalTime);
} else if (totalTime >= 10 && minutes < 10){
System.out.println("0" + minutes + ":" + totalTime);
setTheTime("0" + minutes + ":" + totalTime);
}else {
System.out.println(minutes + ":" + totalTime);
setTheTime(minutes + ":" + totalTime);
}
}
public boolean isTimeRunning() {
return timeRunning;
}
public void timerStarted(){
timeRunning = true;
}
public void timerStopped(){
timeRunning = false;
}
public void stopTimer(){
mTimer.cancel();
timerStopped();
resetCounters();
System.out.println("Timer stopped");
}
private void resetCounters() {
totalTime = 0;
minutes = 0;
}
public String getTheTime() {
return theTime.get();
}
public StringProperty theTimeProperty() {
return theTime;
}
public void setTheTime(String theTime) {
this.theTime.set(theTime);
}
}
The UI
public class LureUI extends Application {
private Button button;
private Button button2;
private LureTimer mLureTimer = new LureTimer();
private Label mLabel;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Lure Monitor");
button = new Button("Start Timer");
button2 = new Button("Stop Timer");
button.setOnAction(e -> mLureTimer.startTimer());
button2.setOnAction(e -> mLureTimer.stopTimer());
VBox layout1 = new VBox();
layout1.setSpacing(10);
mLabel = new Label();
mLabel.textProperty().bind(mLureTimer.theTimeProperty());
layout1.getChildren().addAll(mLabel, button, button2);
layout1.setAlignment(Pos.CENTER);
Scene scene = new Scene(layout1, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
}
When I run this I get an Exception...
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
My goal is to get the mLabel
in the UI class to update from the theTimer()
method which uses timePrint()
set the time.
From reading other posts I can see that a solution is Platform.runLater()
, but this runs a new Runnable object, how would I achieve the same outcome but with a TimerTask?