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

用户测试

我有一个TextField,用户输入薪水。TF有一个基于默认语言环境的TextFormatter。在TextField旁边有一个标签,在此标签中,我要显示格式化为Currency的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()));

很好的答案是,当用户想要输入值时,他将需要删除所有数字,但要删除美元符号,例如,如果用户输入不带美元符号的值,那么新值将不被接受。

这就是为什么我要在“标签”中以货币显示“格式化的”值,而不使用“货币格式化器”的原因。谢谢。

用户测试

这是我使用的解决方案

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章