Vaadin Flow V14:如何实现TextField失焦时的数字格式化?
在Vaadin 14中实现TextField失焦自动格式化数字(千分位)
Vaadin 14的Binder默认不会像V8那样在字段失焦时自动将模型值格式化后回显到UI,结合你的场景(无法使用writeBean/readBean),可以通过给TextField添加失焦监听器,手动完成输入值的转换与格式化回显,具体实现如下:
步骤1:定义数字格式化器
先创建一个符合需求的数字格式化器,用来将BigDecimal转为带千分位的字符串:
// 可根据业务需求调整格式,比如无小数位用"#,##0" private final DecimalFormat numberFormatter = new DecimalFormat("#,##0.00");
步骤2:在绑定字段后添加失焦监听器
基于你原有的绑定代码,补充监听器逻辑:
TextField textFieldNetWeight = new TextField(); Binder<YourBeanClass> binder = new Binder<>(YourBeanClass.class); // 原有的绑定逻辑 BindingBuilder<?, ?> bb = binder.forField(textFieldNetWeight); StringToBigDecimalConverter converter = new StringToBigDecimalConverter("Failed to convert"); ((BindingBuilder<?, String>) bb).withConverter(converter); // 绑定到Bean对应的属性(替换为你的实际属性方法) bb.bind(YourBeanClass::getNetWeight, YourBeanClass::setNetWeight); // 添加失焦监听器,处理格式化逻辑 textFieldNetWeight.addBlurListener(event -> { String inputValue = textFieldNetWeight.getValue(); try { // 通过转换器将输入字符串转为BigDecimal BigDecimal value = converter.convertToModel(inputValue, null); if (value != null) { // 将格式化后的字符串写回TextField textFieldNetWeight.setValue(numberFormatter.format(value)); } } catch (ConversionException e) { // 转换失败时的处理(可根据业务调整) textFieldNetWeight.setErrorMessage(e.getMessage()); textFieldNetWeight.setInvalid(true); } });
关键说明
- 格式化器的格式可按需调整,比如支持负数、不同小数位数等;
- 转换失败时的逻辑可灵活处理,比如保留原输入、清空字段或显示错误提示;
- 该方式既保留了你原有的
setBean/getBean绑定逻辑,又实现了失焦自动格式化的效果。
内容的提问来源于stack exchange,提问作者aha
相关产品推荐
相关产品推荐

