【发布时间】:2015-01-19 02:25:36
【问题描述】:
我正在尝试实现一个涉及 2 个字段计算的 GUI。我的模型有 2 个属性和一个绑定。
ObjectProperty<BigDecimal> price = new SimpleObjectProperty<>();
ObjectProperty<BigDecimal> quantity= new SimpleObjectProperty<>();
ObjectBinding<BigDecimal> totalPrice = new ObjectBinding<BigDecimal>() {
{ bind(price,quantity);}
protected BigDecimal computeValue() {
if (price.get() == null || quantity.get() == null) return null;
return price.get().multiply(quantity.get());
}
};
我的 GUI 有 3 个TextField 来匹配价格、金额、总价格。通常,我正在我的属性和我的TextField 之间进行常规绑定
priceTextField.textProperty().bindBidirectional(myModel.priceProperty(), new NumberStringConverter());
现在这有点棘手。如果用户修改价格或数量,它必须更新 TotalPrice(这是绑定到目前为止所做的)。但我希望能够做到以下几点:如果用户更新 TotalPrice,那么它会根据固定价格重新计算数量。
所以问题是:如何创建这样的流程 => TotalPrice 绑定了价格和数量,但数量绑定了 TotalPrice 和价格。当我在totalPriceTextfield 中输入内容时,它应该更新quantityTextField,反之亦然。
谢谢。
****** 编辑 ********
这是一段丑陋的代码,只是为了说明我想要实现的目标(nb:我知道我可以使用Binding.multiply 和其他方法,但我需要未来的项目来实现计算功能)
public class TestOnBindings {
private DoubleProperty price = new SimpleDoubleProperty(10.0);
private DoubleProperty quantity = new SimpleDoubleProperty(1.0);
private DoubleProperty total = new SimpleDoubleProperty(1.0);
private DoubleBinding totalBinding = new DoubleBinding() {
{bind(quantity,price);}
@Override
protected double computeValue() {
return quantity.get()*price.get();
}
};
private DoubleBinding quantityBinding = new DoubleBinding() {
{bind(total,price);}
@Override
protected double computeValue() {
return total.get()/price.get();
}
};
public TestOnBindings(){
total.bind(totalBinding); //should really not do that, looks ugly
quantity.bind(quantityBinding); //now you're asking for troubles
}
public void setPrice(Double price){
this.price.set(price);
}
public void setQuantity(Double quantity){
this.quantity.set(quantity);
}
public void setTotal(Double total){
this.total.set(total);
}
public Double getTotal(){
return total.get();
}
public Double getQuantity(){
return quantity.get();
}
public static void main(String[] args) {
TestOnBindings test = new TestOnBindings();
test.setQuantity(5.0);
System.out.println("Total amount = " + test.getTotal());
}
}
还有明显的好错误:
线程“main”java.lang.RuntimeException 中的异常:无法设置绑定值。 在 javafx.beans.property.DoublePropertyBase.set(DoublePropertyBase.java:142)
【问题讨论】:
标签: java data-binding javafx javabeans