Vaadin 8 - 如何绑定 RadioButtonGroup 的项目?

Kas*_*rer 4 java vaadin vaadin8

我正在制作一个包含许多 TextFields 和 ComboBoxes 和 CheckBoxes 的视图,其中它们的值由单个 Binder 处理。没有问题。

但是:现在我想在视图中添加 3 个 RadioButton,这些值应该来自同一个 Binder。每个 RadioButton 绑定到不同的布尔字段,这些字段中只有 1 个可以同时为真(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
Run Code Online (Sandbox Code Playgroud)
// 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));
Run Code Online (Sandbox Code Playgroud)

pir*_*rho 5

我建议考虑一些不同的方法。单选按钮通常用于将值分配给单个属性 -RadioButtonGroup是单个表单字段 - 而不是属性或字段列表,所以我想这就是您找不到直接解决方案的原因。

如果可能,将您的三个更改booleanenum类似:

public enum RadioButtonValue {
   foo, bar, foobar;
}
Run Code Online (Sandbox Code Playgroud)

这应该提供兼容的功能,因为您希望一次只限制三个布尔值之一为真。

有那么类:

public class RadioButtonBean {
   @Getter @Setter // Lombok
   private RadioButtonValue radioButtonValue;
   // replaces boolean foo, bar, foobar;
}
Run Code Online (Sandbox Code Playgroud)

允许您轻松进行绑定:

RadioButtonGroup<RadioButtonValue> radioGroup = new RadioButtonGroup<>();
radioGroup.setCaption("Radiobutton group");
// populate with enum values as title or use setItemCaptionGenerator(...);
radioGroup.setDataProvider(
    new ListDataProvider<RadioButtonValue>( 
        Arrays.asList( RadioButtonValue.values() )
    )
);

final RadioButtonBean bean = new RadioButtonBean();
Binder<RadioButtonBean> binder = new Binder<>();
binder.setBean(bean);
binder.forField(radioGroup).bind(RadioButtonBean::getRadioButtonValue,
        RadioButtonBean::setRadioButtonValue );
// uncomment for testing it
//      radioGroup.addValueChangeListener( vc -> {
//         Notification.show("bean enum value: "+ bean.getRadioButtonValue() );
//      });
Run Code Online (Sandbox Code Playgroud)

如果不可能将booleans更改为enum那么我认为最简单的方法是稍微更改上面的内容:

  1. 根本不要绑定无线电组。
  2. 实现ValueChangeListener根据选定的枚举在 bean 中设置相应的布尔值。