【发布时间】:2021-03-03 02:41:30
【问题描述】:
我正在制作一个包含许多 TextField、ComboBox 和 CheckBox 的视图,它们的值由单个 Binder 处理。那里没问题。
但是:现在我想在视图中添加 3 个 RadioButton,这些值应该来自同一个 Binder。每个 RadioButton 都绑定到不同的布尔字段,其中只有一个字段可以同时为真(RadioBoxes 的完美要求)。
问题#1:没有简单的 RadioButton 的组件(就像 CheckBox 一样),我只能找到 RadioButtonGroup。所以我想我将不得不与那个合作。
问题 #2:在Vaadin Docs 中明确表示:
CheckBoxGroup 组件的优点在于它维护了单个复选框对象,您可以轻松获取当前选中项的数组,并且可以轻松更改单个复选框的外观组件并将其与 Binder 一起使用。
但我找不到绑定RadioButtonGroup 项的方法,也找不到任何提及它的地方。
有没有办法在 RadioButtonGroup 中绑定单个项目?
如果不是,那么我担心我将不得不使用 CheckBoxes,而 RadioButtons 将是一种更合乎逻辑的方法。
这里有一些代码来演示我想要完成的事情:
// FooBar Class
private boolean foo = true;
private boolean bar = false;
private boolean fooBar = false;
// constructor, getters and setters
// My View
Binder<FooBar> binder = new Binder<>();
binder.setBean(new FooBar());
// this CheckBox works perfectly fine like this
Checkbox cb = new CheckBox();
cb.setCaption("Foo");
binder.forItem(cb)
.bind(f -> f.isFoo, (f, b) -> f.setFoo(b));
// this part is where I'm confused
RadioButtonGroup<String> rbg = new RadioButtonGroup<>();
rbg.setItems("Foo", "Bar", "FooBar");
// how can i bind each RadioButton to different fields of my FooBar Bean?
// because getItem() does not exist
binder.forItem(rbg.getItem(0)).bind(f -> f.isFoo, (f, b) -> f.setFoo(b));
binder.forItem(rbg.getItem(1)).bind(f -> f.isBar, (f, b) -> f.setBar(b));
binder.forItem(rbg.getItem(2)).bind(f -> f.isFooBar, (f, b) -> f.setFooBar(b));
【问题讨论】: