I'm having some troubles using multithreads in JavaFX. I'm working on simple timer application and when I try to update my timer label, application just freezes. I know about Platform.runLater(), but dont't understand how to use it in this situation.
Here are my controller class :
public class Controller{
@FXML
Label timerField;
@FXML
Button startButton;
public void startCounting(ActionEvent actionEvent) {
Platform.runLater(new TimerHandler(timerField));
}
and class where the label is updating :
public class TimerHandler implements Runnable {
Label timerField;
public TimerHandler(Label timerField) {
this.timerField = timerField;
}
int intSecondTime = 0;
int intMinuteTime = 0;
int intHourTime = 0;
String strSecondTime = "";
String strMinuteTime = "";
String strHourTime = "";
String labelTime = "";
public void displayTimer() {
timerField.setText(labelTime);
System.out.println(labelTime);
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
intSecondTime++;
if (intSecondTime == 60) {
intSecondTime = 0;
intMinuteTime++;
if (intMinuteTime == 60) {
intMinuteTime = 0;
intHourTime++;
}
}
if (intSecondTime < 10) {
strSecondTime = "0" + intSecondTime;
} else strSecondTime = "" + intSecondTime;
if (intMinuteTime < 10) {
strMinuteTime = "0" + intMinuteTime;
} else strMinuteTime = "" + intMinuteTime;
if (intHourTime < 10) {
strHourTime = "0" + intHourTime;
} else strHourTime = "" + intHourTime;
labelTime = strHourTime + ":" + strMinuteTime + ":" + strSecondTime;
displayTimer();
Thread.sleep(1000);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}