vaadin表格浮点字段

sok*_*kie 2 java forms input vaadin

我有一个带有表单的vaadin应用程序,我使用beanitem作为数据源.在beanitem内部我有一个默认值为0.0的浮点值.如果我输入一个高值,如123123123并提交(它保存到数据库),当我尝试在表单内编辑该字段时,我得到1.23123123E9作为值,为什么?当我编辑我仍然传递beanitem与其中的数据,为什么它不在文本字段中正确显示我的价值?

我知道如果我必须显示值,我可以使用十进制格式,但这是在窗体内,并且vaadin知道它是一个浮点数,所以它应该相应地处理它吗?或者我必须自己在表单字段工厂中进行格式化吗?

PS:你怎么能为表单里面的值设置一个显示模式?我已经读过你可以实现bean里面的get字段并让它返回一个字符串,这是正确的方法吗?

Ren*_*nov 6

实际上Vaadin行为正确,但它遵循规模规则(Yogendra Singh已经提到过)请看一个例子

在此输入图像描述

还请检查以下内容:

    float value1 = 12.0f;
    float value2 = 123123123;

    BeanItem<Float> item1 = new BeanItem<Float>(value1);
    BeanItem<Float> item2 = new BeanItem<Float>(value2);

    System.out.println(" result 1: " + item1.getBean());
    System.out.println(" result 2: " + item2.getBean());
Run Code Online (Sandbox Code Playgroud)

结果:

result 1: 12.0
result 2: 1.2312312E8
Run Code Online (Sandbox Code Playgroud)

所以正确的解决方案(我可以看到它)如下所示:

  1. 定义自己的Bean.没有理由让BeanItem包装浮点值.
  2. 定义PropertyFormatter(示例)
  3. 需要注意的是,不应该返回String而不是正确的数据类型.它会影响编辑,验证等.

PropertyFormatter示例:

/** Integer formatter that accepts empty values. */
public class LenientIntegerFormatter extends PropertyFormatter {

    public LenientIntegerFormatter(Property propertyDataSource) {
        setPropertyDataSource(propertyDataSource);
    }

    @Override
    public Object parse(String formattedValue) throws Exception {
        if ("".equals(formattedValue))
            return null;
        else
        return Integer.valueOf(formattedValue);
    }

    @Override
    public String format(Object value) {
        if (value == null)
            return "";

        return ((Integer) value).toString();
    }

    @Override
    public Class<?> getType() {
        return String.class;
    }
}
Run Code Online (Sandbox Code Playgroud)

它可能看起来有点可怕,但这是灵活性的代价.Custom Bean允许使用表视图,表单等,而无需任何重大更改.基本上,这是Vaadin UI背后的数据模型.

在此输入图像描述

第9章将组件绑定到数据

自定义Bean示例:

public class Bean implements Serializable {
    String name;
    float value;

    public Bean(String name, float newValue) {
        this.name   = name;
        this.value = newValue;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getValue() {
        return value;
    }

    public void setValue(float newValue) {
        this.value = newValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

只是为了提供所有必要的见解:

 Bean bean = new Bean("Test", value1);
    BeanItem<Bean> beanItem = new BeanItem<Bean>(bean);
    for(Object propertyId: beanItem.getItemPropertyIds()) {
        System.out.println(" Property: '" + propertyId + 
                           "' value: " + beanItem.getItemProperty(propertyId));
    }
Run Code Online (Sandbox Code Playgroud)

将打印:

Property: 'name' value: Test
Property: 'value' value: 12.0
Run Code Online (Sandbox Code Playgroud)