2011-09-21 63 views
0

我有2个名为“qty”和“amount”的JtextFields。当用户键入数量时,该值在某些计算下消失,并将最后一个值设置为数量文本字段。我已经将这两个文本域绑定到了bean绑定类的属性。当用户键入数量时,负责该文本字段的属性被调用,然后我调用了qty的firepropertychange以及数量的firepropertychange,以根据数量更新数量的值。这个效果很好。当qty的文本框的值被退格按钮删除时,qty的值也会改变。但是当qty文本框为空时,文本框的数量保持其最后的值(假设qty的数字为'22'并且数量为textfield显示'44',当退格被按下时,数字为'2'且金额的showwing值为'4',但当qty中的最后一个值'2'被删除时,金额文本字段显示为'4')。文本字段的数量应该显示为零。JTextField BeansBinding

这个请求的任何解决方案?

+0

听起来像转换字符串 - >号码不能处理空/空输入(其中大部分格式化不能,你必须告诉他们或你转换器接受一个0) – kleopatra

+0

我还是新的beanbinding。你能告诉我样品转换课程如何做到这一点吗? –

+0

我认为,当JTextField中没有任何字符时(前面有一些字符时),JtextField的值是“”不为空或为空。这就是我的想法和不知道确切的reasone。 –

回答

1

刚刚检查了默认的转换器:它们不处理空/空,你必须实现一个可以做和设置绑定。喜欢的东西,看到取消对转换器设定的区别:

@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); 
    } 
}; 
+0

感谢您的代码。我在我的应用程序中使用它。它工作得很好。非常感谢你:)我还在转换器中遇到了另一个问题。我可以用你的想法解决这个问题。很高兴 :) –