1

I have a TextField, where user input salary. The TF have a TextFormatter based on Default Locale. next to The TextField there is a Label, In this Label I want to Show the TextField Text Formatted as Currency, For all of This I use this Code:

TextField text = new TextField();
Label show = new Label();

TextFormatter<Number> formatter = new TextFormatter<>(new FormatStringConverter<>(DecimalFormat.getNumberInstance()));

text.setTextFormatter(formatter);

show.textProperty().bind(Bindings.concat(text.getTextFormatter().valueProperty().asString())
.concat(" ").concat(Currency.getInstance(Locale.getDefault()).getCurrencyCode()));

return new HBox(text, show);

The result: enter image description here

As you can see The label text is not formatted as a number - because no formatter have been applied -. So my Question is how Can I make the text of the label formatted and the same time binded with the TextField TextProperty.

Someone May Ask: Why not use a currency formatter instead of number formatter like:

new TextFormatter<>(new FormatStringConverter<>(DecimalFormat.getCurrencyInstance()));

well The answer is, when the user wants to enter the value, he will need to remove ALL digits BUT the the dollar sign for example, if the user enter a value without the dollar sign, the new value will not be accepted.

That's why I want to show The Formatted value as a currency in a Label, and NOT use the Currency Formatter. Thanks.

usertest
  • 2,140
  • 4
  • 32
  • 51

2 Answers2

1

This is not quite the same format, but may be what you need.

    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    show.textProperty().bind(Bindings.createStringBinding(
        () -> formatter.getValue() == null 
              ? "" 
              : currencyFormat.format(formatter.getValue().doubleValue()),         
        formatter.valueProperty()));
James_D
  • 201,275
  • 16
  • 291
  • 322
1

Here Is The Solution I Used

text.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> {
        if(!newPropertyValue){
            show.setText(form.format(formatter.getValue().doubleValue()));
        }
    });
usertest
  • 2,140
  • 4
  • 32
  • 51