0

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();
    }
}
}
ChpokHead
  • 13
  • 4
  • 1
    you need to understand, that `Platform.runLater` will call your `TimerHandler` on the main(UI) thread. Next, when you call `Thread.sleep(1000);` you block the main thread. That's why your application freezes. – JohnnyAW Nov 22 '17 at 21:37
  • 1
    There's also no point in calling `Platform.runLater(...)` from an event handler, as the event handler is already executed on the fx application thread. – James_D Nov 22 '17 at 23:04
  • Oh, I got it . Thank you:) – ChpokHead Nov 23 '17 at 05:25

0 Answers0