我有两个JtextFields分别叫"qty"one_answers"amount"。当用户键入"数量"时,将对该值进行一些计算,并将最后一个值设置为amount textfield。我已经将这2个文本字段绑定到beansbinding类的属性。当用户输入qty时,负责该文本字段的属性被调用,然后我调用了qty的firepropertychange以及amount的firepropertychange来根据qty更新amount的值。这很有效。此外,当qty的文本字段的值被删除与退格按钮的数量的值也改变。但是当qty文本字段为空时,amount文本字段保持其最后一个值(假设qty有一个数字'22',amount文本字段显示'44',当按下退格键时,数字为'2',amount的显示值为'4',但是当qty中的最后一个值'2'也被删除时,amount文本字段显示'4')。我希望金额文本字段应该显示为零。
有什么解决办法吗?
只是检查了默认的转换器:它们不处理null/empty,你必须实现一个可以处理null/empty的转换器,并将其设置为绑定。例如,要查看差异,取消对转换器设置的注释:
@SuppressWarnings({ "rawtypes", "unchecked" })
private void bind() {
BindingGroup context = new BindingGroup();
AutoBinding firstBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
// this is some int property
this, BeanProperty.create("attempts"),
fields[0], BeanProperty.create("text"));
context.addBinding(firstBinding);
// firstBinding.setConverter(INT_TO_STRING_CONVERTER);
context.bind();
}
static final Converter<Integer, String> INT_TO_STRING_CONVERTER = new Converter<Integer, String>() {
@Override
public String convertForward(Integer value) {
return Integer.toString(value);
}
@Override
public Integer convertReverse(String value) {
if (value == null || value.trim().length() == 0) return 0;
return Integer.parseInt((String) value);
}
};