简体   繁体   中英

How can I update label's text using Timeline in JavaFX?

So basically I am creating a simulation system that simulates temperature rising and falling in a room due to certain factors. I want to output how the temperature changes over time using a Label. I've tried using Timeline in this way:

                Timeline timeline = new Timeline();
                List<KeyValue> values = new ArrayList<KeyValue>();
                values.add(new KeyValue(label.textProperty(), "1"));
                values.add(new KeyValue(label.textProperty(), "2"));
                values.add(new KeyValue(label.textProperty(), "3"));
                values.add(new KeyValue(label.textProperty(), "4"));


                timeline.getKeyFrames().add(new KeyFrame(new Duration(4000), values.toArray(new  KeyValue[values.size()])));
                timeline.play();

I expected this code to show "1" and then "2", but it just waits 4 seconds and changes label's text to "4".

How can I achieve the gradual changing I want?

Thanks!

The TimeLine did exactly what you have programmed (change labels text four times in a row, after 4 seconds).

If you want to change the labels text one after another with a small delay, you will have to use more KeyFrames:

timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(4), new KeyValue(label.textProperty(), "1")));
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(5), new KeyValue(label.textProperty(), "2")));
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(6), new KeyValue(label.textProperty(), "3")));

and so on..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM