Roland
Roland

Reputation: 18415

How to bind property using a formatter

I have a label and a double property. I'd like to output the value with the postfix "$", i. e. "200.50 $". How can I do this with JavaFX? I thought about using binding like this:

@FXML Label label;
DoubleProperty value;
...
Bindings.bindBidirectional( label.textProperty(), valueProperty(), NumberFormat.getInstance());

But haven't found a way to append the " $" to the text.

Thank you very much for the help!

Upvotes: 3

Views: 5856

Answers (3)

Roland
Roland

Reputation: 18415

Thanks to ItachiUchiha and NDY I got on the right track to the answer. I'll have to use a StringConverter like this:

  public class MoneyStringConverter extends StringConverter<Number> {

    String postFix = " $";
    NumberFormat formatter = numberFormatInteger; 

    @Override
    public String toString(Number value) {

        return formatter.format( value) + postFix;

    }

    @Override
    public Number fromString(String text) {

      try {

        // we don't have to check for the symbol because the NumberFormat is lenient, ie 123abc would result in the value 123
        return formatter.parse( text);

      } catch( ParseException e) {
        throw new RuntimeException( e);
      }

    }

  }

And then I can use it in the binding:

Bindings.bindBidirectional( label.textProperty(), valueProperty(), new MoneyStringConverter());

Upvotes: 2

ItachiUchiha
ItachiUchiha

Reputation: 36722

You can just concat it to the value using

label.textProperty().bind(Bindings.concat(value).concat("$"));

Upvotes: 1

NDY
NDY

Reputation: 3557

Something like this should work.

Bindings.format("%.2f $", myDoubleProperty.getValue());

Now you can bind it

 label.textProperty.bind(Bindings.format("%.2f $", myDoubleProperty.getValue());

If you want to use the NumberFormat instance, just format the value of the myDoubleProperty with it.

NumberFormat formatter = NumberFormat.getInstance();
formatter.setSomething();
formatter.format(myDoubleProperty.getValue());

Now add it to our Bindings.format.

Edit:

Included inputs of ItachiUchiha.

Upvotes: 4

Related Questions