0

I'm trying to update a label once per second using a TimerTask which changes the value of a StringProperty:

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

To update the label I've added a ChangeListener to the StringProperty which changes the label's text based on the String:

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

But since I have to run this operation using the runLater method, the label isn't updated regularly. How do I achieve an update that occurs once a second?

Kaes3kuch3n
  • 123
  • 1
  • 10

2 Answers2

1

For those interested in the solution: Using a timeline instead of the TimerTask works perfectly fine:

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

Thanks to @JKostikiadis for sharing this post: https://stackoverflow.com/a/16138351/4167500

Kaes3kuch3n
  • 123
  • 1
  • 10
0

You can try this too. You need a runnable to make it work:

   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);
}
zzdhxu
  • 379
  • 6
  • 22