Search code examples
javafxbindingformatter

How to bind an ObjectBinding<BigDecimal> to a Label with a Formatter?


I have an ObservableList<Items> items and can calculate the sum of the items prices (BigDecimal) and bind the result to a labels text property in the following way:

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

But now i would like to use a formatter (DecimalFormat) instead of the asString("%.2f €") method to be more flexible and i don't know how to realize that. It would be nice if someone could show how to implement the binding with a formatter (without the use of a listener when possible). Thank you.


Solution

  • With the help of Slaw's comment i was able to figure out the following working solution:

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

    If there is an even more eloquent way, please let me know.