尝试更新标签文本

时间:2017-11-22 20:44:20

标签: java multithreading javafx

我在JavaFX中使用多线程遇到了一些麻烦。我正在处理简单的计时器应用程序,当我尝试更新我的计时器标签时,应用程序就会冻结。我知道Platform.runLater(),但在这种情况下不了解如何使用它。

这是我的控制器类:

public class Controller{

@FXML
Label timerField;

@FXML
Button startButton;


public void startCounting(ActionEvent actionEvent) {
    Platform.runLater(new TimerHandler(timerField));

}

和标签更新的类:

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();
    }
}
}

0 个答案:

没有答案