使用FloatProperty将ObjectProperty绑定到其他属性

时间:2017-05-28 15:07:35

标签: java javafx javabeans

我有一个Article类,里面有一些Properties

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

    ...
}

我有一个Sale课程,可以引用一篇文章。

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

如何正确绑定整个属性?现在,如果我做这样的事情,总不会在tableView上改变。

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

我想我应该参考文章属性而不是价值,但我不知道如何。

2 个答案:

答案 0 :(得分:2)

您可以使用Bindings.selectFloat

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

答案 1 :(得分:1)

你可以这样做:

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

    FloatProperty articlePriceProperty = new SimpleFloatProperty();
    if (this.article != null) {
        articlePriceProperty.bind(article.priceProperty());
    }
    this.article.addListener((obs, oldArticle, newArticle) -> {
        articlePriceProperty.unbind();
        if (newArticle == null) {
            articlePriceProperty.set(0);
        } else {
            articlePriceProperty.bind(newArticle.priceProperty());
        }
    });
    this.total.bind(Bindings.multiply(Bindings.subtract(articlePriceProperty, Bindings.multiply(articlePriceProperty(), this.discount)), this.quantity));
}