Search code examples
javajavafxjavabeans

Bind ObjectProperty with FloatProperty inside to other property


I have an Article class with some Properties inside.

public class Article {
    private IntegerProperty id;
    private StringProperty name;
    private StringProperty description;
    private FloatProperty price;

    public Article(int id, String name, String description, float price) {
        this.id = new SimpleIntegerProperty(id);
        this.name = new SimpleStringProperty(name);
        this.description = new SimpleStringProperty(description);
        this.price = new SimpleFloatProperty(price);
    }

    ...
}

And I have a Sale class that makes reference to one Article.

public class Sale {
    private IntegerProperty id;
    private ObjectProperty<Article> article;
    private FloatProperty discount;
    private IntegerProperty quantity;
    private FloatProperty total;

    public Sale(int id, Article article, float discount, int quantity) {
        this.id = new SimpleIntegerProperty(id);
        this.article = new SimpleObjectProperty<>(article);
        this.discount = new SimpleFloatProperty(discount);
        this.quantity = new SimpleIntegerProperty(quantity);
        this.checked = new SimpleBooleanProperty(false);

        this.total = new SimpleFloatProperty();
        this.total.bind(Bindings.multiply(Bindings.subtract(this.article.get().priceProperty(), Bindings.multiply(this.article.get().priceProperty(), this.discount)), this.quantity));
    }

    public void setArticle(Article article) {
        this.article.set(article);
    }
    ...
}

How can I bind the total property properly? Now if I do something like this, total won't change dinamically on tableView.

Sale sale = new Sale(0, article1, 0.1f, 2);
sale.setArticle(article2); 

I suppose I should make reference to the articleProperty not the value but I don't know how to.


Solution

  • You could use Bindings.selectFloat:

    this.total.bind(Bindings.multiply(Bindings.selectFloat(this.article, "price")
                                              .multiply(this.quantity),
                                      Bindings.subtract(1d, this.discount)));