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?