javafx:将标签文本 属性 与 TextField 的 + FORMAT 结果绑定

javafx: bind label text property with TextField's + FORMAT result

我有一个 TextField,用户可以在其中输入薪水。 TF 有一个基于默认语言环境的 TextFormatter。在 TextField 旁边有一个标签,在这个标签中我想显示格式化为货币的 TextField 文本,为此我使用这个代码:

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

结果:

如您所见,标签文本未格式化为数字 - 因为未应用格式化程序 -。 所以我的问题是如何使标签的文本格式化并同时与 TextField TextProperty 绑定。

有人可能会问:为什么不使用货币格式化程序而不是数字格式化程序,例如:

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

答案是,当用户想要输入值时,他将需要删除除美元符号之外的所有数字,例如,如果用户输入一个没有美元符号的值,则新值将不会被接受。

这就是为什么我想在标签中将格式化值显示为货币,而不是使用货币格式化程序。谢谢

这不是完全相同的格式,但可能是您需要的。

    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    show.textProperty().bind(Bindings.createStringBinding(
        () -> formatter.getValue() == null 
              ? "" 
              : currencyFormat.format(formatter.getValue().doubleValue()),         
        formatter.valueProperty()));

这是我使用的解决方案

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