Dea5
Dea5

Reputation: 131

How to bind a JavaFX progressBar to a double value stored in an Object

I'm still learning and I hope you can help me:

I have an Object myObject that stores a double value, which represents the percentage progress of a calculation (When myObject is inizialized, the value is 0D, and often updated inside myObject itself until it reaches 100D).


I'd like to bind this double value to a javaFX progressBar, so that when the value stored in myObject is updated, so the progressBar will.


I heard something about Observer/Observable/Listener.
Is this what I am looking for? Can someone show me some code so that I can understand?

Thanks!

Upvotes: 1

Views: 1488

Answers (1)

Baron
Baron

Reputation: 161

I know that I am five months late, but I just had a very similar problem, and during my searching came across your question that nobody else answered. Nobody answered mine either, so I kept digging until I figured it out myself. I assume that if I stumbled over your post looking for an answer, someone else eventually would too, so I wanted to share my answer.

Yes, what you are looking for is an ObservableDouble. Assuming that you are able to change myObject to be a double:

DoubleProperty barUpdater = new SimpleDoubleProperty(myObject);

And, somewhere in your initialize (or wherever you use the bar), bind your bar to it:

progressBar.progressProperty().bind(barUpdater);

Then, when you wish to update your ProgressBar, you can set the value of the updater to something else.

barUpdater.set(myObject);

In doing so, you will update the ObservableDouble that your ProgressBar is listening for, causing it to update it's value.

See my answer here for an example of the code in use if you need it.

Upvotes: 3

Related Questions