[英]vaadin form float field
我有一個帶有表單的vaadin應用程序,我使用beanitem作為數據源。 在beanitem內部,我有一個默認為0.0的浮點值。為什么? 當我編輯我仍然傳遞beanitem與其中的數據,為什么它不在文本字段中正確顯示我的價值?
我知道如果我必須顯示值,我可以使用十進制格式,但這是在窗體內,並且vaadin知道它是一個浮點數,所以它應該相應地處理它嗎? 還是我必須自己在表單字段工廠中格式化它?
PS:如何為表單中的值設置顯示模式?我讀過您可以在Bean中實現字段的獲取,並使其也返回字符串,這是正確的方法嗎?
實際上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());
結果:
result 1: 12.0
result 2: 1.2312312E8
所以正確的解決方案(我可以看到它)如下所示:
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;
}
}
它可能看起來有點可怕,但這是靈活性的代價。 Custom Bean允許使用表視圖,表單等,而無需任何重大更改。 基本上,這是Vaadin UI背后的數據模型。
自定義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;
}
}
只是為了提供所有必要的見解:
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));
}
將打印:
Property: 'name' value: Test
Property: 'value' value: 12.0
toString()
內部調用toString(float)這是文檔對toString(float)
說法
否則,結果是一個字符串,表示參數的符號和大小(絕對值)。 如果符號為負數,則結果的第一個字符為' - '('\\ u002D'); 如果符號為正,則結果中不顯示符號字符。 至於大小m:
如果m大於或等於10-3但小於107,那么它表示為m的整數部分,十進制形式,沒有前導零,后跟'。' ('\\ u002E'),后跟一個或多個十進制數字,表示m的小數部分。
如果m小於10-3或大於或等於107,則設n為唯一整數,使得10n≤m<10n + 1; 然后將a設為m和10n的數學精確商,使1≤a<10。然后將幅度表示為a的整數部分,作為單個十進制數字,后跟'。' ('\\ u002E'),后跟表示a的小數部分的十進制數字,后跟字母'E'('\\ u0045'),后跟n表示為十進制整數,由Integer方法生成。的toString(INT)。
要創建浮點值的本地化字符串表示形式,請使用NumberFormat的子類。
希望這有助於您了解WHY
以及HOW
修復它,即使用您在現場工廠中提到的DecimalFormat
並返回字符串表示以顯示用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.