如何使用<BigDecimal>格式化程序将对象绑定绑定到标签?



我有一个ObservableList<Items> items,可以计算项目价格的总和(BigDecimal(,并通过以下方式将结果绑定到标签文本属性:

totalSumLabel.textProperty().bind(
Bindings.createObjectBinding(() -> items.stream()
.map(item -> item.getPrice())
.reduce(BigDecimal.ZERO, BigDecimal::add),
items)
.asString("%.2f €"));

但是现在我想使用格式化程序(DecimalFormat(而不是asString("%.2f €")方法更灵活,我不知道如何实现这一点。如果有人可以展示如何使用格式化程序实现绑定(尽可能不使用侦听器(,那就太好了。谢谢。

在Slaw的评论的帮助下,我能够找出以下工作解决方案:

ObjectBinding<BigDecimal> totalSumObjectBinding = Bindings.createObjectBinding(() ->
items.stream()
.map(item -> item.getPrice())
.reduce(BigDecimal.ZERO, BigDecimal::add),
items);
DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.getDefault());
StringBinding totalSumStringBinding = Bindings.createStringBinding(() ->
formatter.format(totalSumObjectBinding.getValue()), totalSumObjectBinding);
totalSumLabel.textProperty().bind(totalSumStringBinding);

如果有更雄辩的方式,请告诉我。

最新更新