![](/img/trans.png)
[英]Is there a way to set a cell in grid in edit mode with Vaadin 8 grid
[英]Is there a way to set a validation and edit a long value in an editable Vaadin 8 Grid
我有一個Vaadin 8網格,我想在其中將一列設置為可編輯。 為此,我有Food.calories
較長的地方(是的,在這種情況下可能是整數,但是請記住,這是一個示例,我的特定用例需要很長的時間):
Binder<Food> binder = foodGrid.getEditor().getBinder();
TextField caloriesTextField = new TextField();
binder.forField(caloriesTextField)
.withValidator(CustomCaloryValidator::isValidValue, "Must be valid a positive amount")
.withConverter(new StringToCaloriesConverter("Must be an integer"))
.bind(Food::getCalories, Food::setCalories);
// This line fails with the error because the types do not match.
foodGrid.addColumn(Food::getCalories, new NumberRenderer(myNumberFormat))
.setEditorComponent(new TextField(), Food::setCalories);
不幸的是,這不起作用,並出現以下錯誤:
類型參數“ C”的推斷類型“ C”不在其范圍內; 應該實現'com.vaadin.data.HasValue'
我到處都可以看到,除了簡單的編輯之外,找不到任何示例。 演示采樣器的確有一個使用滑塊的更復雜的示例,但我無法弄清楚如何從該示例中推斷...
我了解錯誤,它正在嘗試將long映射到String。 但是我找不到一種將轉換器添加到addColumn使其工作的方法...
首先,主要問題是活頁夾未指定泛型類型,它需要是:
Binder<Food> binder = foodGrid.getEditor().getBinder();
並不是:
Binder binder = foodGrid.getEditor().getBinder();
話雖這么說,還有其他陷阱。 首先,當您執行forField()
,需要跟蹤該綁定,以便以后可以使用該列對其進行設置。 這一點對我來說還不清楚。 具體來說,您需要:
Binder.Binding<Food, Long> caloriesBinder = binder.forField(caloriesTextField)
.withValidator(CustomCaloryValidator::isValidValue, "Must be valid a positive amount")
.withConverter(new StringToCaloriesConverter("Must be an integer"))
.bind(Food::getCalories, Food::setCalories);
我不確定100%的卡路里數,因為我的代碼不同,這是一個示例,但是您需要該綁定。 然后,您執行該綁定並執行以下操作:
foodGrid.getColumn("calories").setEditorBinding(caloriesBinding);
這樣可以使用正確的編輯器。 這在文檔中,但是示例非常簡單,所以我錯過了。
下一步(根據要顯示的內容非常重要)是添加渲染器,否則可能會遇到一些奇怪的問題。 例如,如果您用很長時間存儲貨幣,則需要將其轉換為顯示貨幣金額。 同樣,如果您使用的是日期,則可能還需要設置其格式。 然后,您需要添加渲染器。 我能找到沒有編譯錯誤(類型不匹配)的唯一方法是:
((Grid.Column<Food, Long>)foodGrid.getColumn("calories")).setRenderer(new CaloriesRenderer());
為了完整起見,您需要啟用以下功能:
foodGrid.getEditor().setEnabled(true);
最后,如果表是更大的bean的一部分,那么您需要調用foodGrid.setItems()
,您不能僅僅依賴binder.readBean()
因為它不能接受列表。 因此,例如,如果代替食物的是由多種成分組成的一餐豆,那么即使可以binder.readBean(meal)
,也不能binder.readBean(meal)
也不能binder.readBean(meal.getIngredients)
binder.readBean(meal)
其余形式的binder.readBean(meal)
。 我可以使其起作用的唯一方法是:
binder.readBean(meal);
foodGrid.setItems(meal.getIngredients);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.