JavaFX:使用StringProperty和ChangeListener定期基于TimerTask更新Label

时间:2017-11-25 22:35:25

标签: java javafx timertask

我尝试使用更改StringProperty值的TimerTask每秒更新一次标签:

public class RandomString extends TimerTask {

private StringProperty randomString;
private ArrayList<String> strings;
private Random random;

public RandomString(String... str) {
    randomString = new SimpleStringProperty(this, "randomString", "");
    strings = new ArrayList<>(Arrays.asList(str));
    random = new Random();
}

public String getRandomString() {
    return randomString.get();
}

public StringProperty randomStringProperty() {
    return randomString;
}

public void setRandomString(String randomString) {
    this.randomString.set(randomString);
}

@Override
public void run() {
    int i = random.nextInt(strings.size());
    setRandomString(strings.get(i));
}

public void startTimer() {
    new Timer(true).schedule(this, 0, 1000);
}

要更新标签,我已将ChangeListener添加到StringProperty,后者根据字符串更改标签的文本:

randomString.randomStringProperty().addListener(
            (observable, oldValue, newValue) -> 
                    Platform.runLater(() -> label.setText(newValue)
));

但由于我必须使用runLater方法运行此操作,因此标签不会定期更新。如何实现每秒发生一次的更新?

2 个答案:

答案 0 :(得分:1)

对于那些对解决方案感兴趣的人:使用时间轴代替TimerTask非常合适:

public void startTimer() {
    Timeline timeline = new Timeline();
    timeline.getKeyFrames().add(new KeyFrame(Duration.ZERO, event -> {
        int i = random.nextInt(strings.size());
        setRandomString(strings.get(i));
    }));
    timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(1)));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();
}

感谢@JKostikiadis分享这篇文章:https://stackoverflow.com/a/16138351/4167500

答案 1 :(得分:0)

你也可以尝试一下。你需要一个runnable来使它工作:

   Timer t1 = new Timer();
   private void startTimer() {
    t1.schedule(new TimerTask() {
        @Override
        public void run() {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    label.setText("Testing");
                }
            });
        }
    }, 0, 1000);
}