更新TextField以显示倒数计时器

时间:2017-12-15 12:12:29

标签: javafx timer textfield

我正在尝试在使用Scene Builder 2在JavaFX GUI中创建的TextField中显示最接近0.1秒的计时器。计时器工作正常,但我无法将其显示为实际的倒计时它在TextField中正在进行中,它将在计数完成后从初始设置更改为零。我也尝试使用标签,因为一些论坛的答案似乎表明它会起作用,但它会显示相同的行为。如果我尝试使用Thread循环设置TextField,我会收到StackOverflow错误。

计时器类

    package extrusion;

public class CalibrationTimer {

//  Controller controller = new controller();
    int initialTimerSetting;
    int count;

    public void startTimer() throws InterruptedException {

        for (int count = (initialTimerSetting*10); count >=0; count--){
        Thread.sleep(100);
//      controller.timeSecs.setText(Integer.toString(count)); this invokes a StackOverflow error
        }
    }

    public void setInitialTimer(int setInitialTimer) {
        initialTimerSetting = setInitialTimer;
    }

    public double getInitialTimer() {
        return initialTimerSetting;
    }

    public int getCount() {
        return count;
    }
}

表单控制器

    package extrusion;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

public class Controller implements Initializable{

        CalibrationTimer calTimer = new CalibrationTimer();

        @FXML
        public TextField timeSecs;

        @Override
        public void initialize(URL location, ResourceBundle resources) {
            timeSecs.setText(Double.toString(0.0));

        }

        @FXML
        public void calibrationStartButtonAction(ActionEvent event) throws InterruptedException{
            calTimer.setInitialTimer(Integer.parseInt(timeSecs.getText()));
            calTimer.startTimer();
            timeSecs.setText(Integer.toString(calTimer.getCount()));  //does not count down but returns zero after the count has finished
        }

}

0 个答案:

没有答案