如何使用格式化程序将 ObjectBinding<BigDecimal> 绑定到标签?
How to bind an ObjectBinding<BigDecimal> to a Label with a Formatter?
我有一个 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);
如果有更eloquent的方法,请告诉我。
我有一个 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);
如果有更eloquent的方法,请告诉我。