简体   繁体   中英

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.

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

Try this:

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

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

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