Benj
Benj

Reputation: 289

Binding Label textProperty in JavaFX

I have this code in initialize method JavaFX:

montantPayeProperty = new SimpleDoubleProperty(0);
labelMontantPaye.textProperty().bind(montantPayeProperty.asString());

montantPayeProperty is a DoubleProperty, and labelMontantPaye is a Label.

And I have a button when I click, this method is called :

public void majMontantPaye(Double montantPaye) {
   this.montantPayeProperty = new SimpleDoubleProperty(montantPaye);
}

The problem is that my Label labelMontantPaye is not refreshed automatically with montantPaye when I click in the button. Why?

Thanks.

Upvotes: 1

Views: 2290

Answers (3)

DVarga
DVarga

Reputation: 21829

When you call

labelMontantPaye.textProperty().bind(montantPayeProperty.asString());

you are binding the object pointed by the pointer stored in the textProperty of the Label to the object pointed by the pointer stored in montantPayeProperty.

When you call

this.montantPayeProperty = new SimpleDoubleProperty(montantPaye);

the pointer stored in the montantPayeProperty will point to a new object, but the binding will still be active between the old object and the textProperty. The old object is unmodified, therefore this property does not get updated.

You should not set the pointer to a new object, but set the value stored in the currently pointed object by calling:

montantPayeProperty.setValue(montantPaye);

or by

montantPayeProperty.set(montantPaye);

Upvotes: 4

fabian
fabian

Reputation: 82531

You replace the property, in your setter, so the Label's text property is bound to a different property instance.

A property usually should not be replaced once it's created. Instead the value stored in the property should be modified. The standard for a property value (non-lazy initialisation) would be

private final DoubleProperty value = new SimpleDoubleProperty();

public DoubleProperty valueProperty() {
    return value;
}

public void setValue(double value) {
    this.value.set(value);
}

public double getValue() {
    return value.get();
}

Upvotes: 2

BadVegan
BadVegan

Reputation: 494

Try this:

 public void majMontantPaye(Double montantPaye) {
  this.montantPayeProperty.setValue(montantPaye);
}

Upvotes: 3

Related Questions