编程语言
首页 > 编程语言> > java – 带ComboBox的BeanFieldGroup?

java – 带ComboBox的BeanFieldGroup?

作者:互联网

我正在尝试在我的应用程序中使用BeanFieldGroup创建一个ComboBox组件,但仍然无法做到这一点.我尝试先创建一个组合框,然后在buildAndBind中添加这个组合框,但也不起作用.

我正在尝试这个:

/** person's bean */
@Entity
public class Person{

@Id
@GeneratedValue
private Integer id;

@NotNull
@NotEmpty
@Size(min=5, max=50, message="insert first name")
private String firstName;

@NotNull
@NotEmpty
@Email private String email;

//female or male
private String gender;

//get and set
}

/** app */
public class PersonView extends CustomComponent{
private final BeanFieldGroup<Person> binder = new BeanFieldGroup<Person>(Person.class);
private Person bean = new Person();

    private ComboBox gender;

    public PersonView(){
         VerticalLayout vLayout = new VerticalLayout();
         Field<?> field = null;
         field = binder.buildAndBind("Gender", "gender", ComboBox.class);
         gender = (ComboBox)binder.getField("gender");
         gender.addItem("Male");
         gender.addItem("Female");
         vLayout.addComponent(gender);
    }
}

例外:

/** exception /*
Caused by: com.vaadin.data.fieldgroup.FieldGroup$BindException: Unable to build a field of type com.vaadin.ui.ComboBox for editing java.lang.String
    at com.vaadin.data.fieldgroup.FieldGroup.build(FieldGroup.java:1067)
    at com.vaadin.data.fieldgroup.FieldGroup.buildAndBind(FieldGroup.java:1039)
    at br.ind.ibg.views.CurriculumView.buildLayout(CurriculumView.java:50)
    at br.ind.ibg.views.CurriculumView.<init>(CurriculumView.java:32)
    at br.ind.ibg.views.LoginView.buttonClick(LoginView.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
    ... 37 more

我是怎么做到的

解决方法:

这是个好问题!经过一番调查,我发现了以下解决方案:

您必须创建自定义FieldGroupFieldFactory(为什么会在下面看到):

binder.setFieldFactory(new DefaultFieldGroupFieldFactory() {

    @Override
    public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {

        if (type.isAssignableFrom(String.class) && fieldType.isAssignableFrom(ComboBox.class)) {
            return (T) new ComboBox();
        }

        return super.createField(type, fieldType);
    }

});

之所以:

如果您查看了vaadin源代码DefaultFieldGroupFieldFactory.java,您将看到最后只有在您将Enum作为“属性数据源”提供时才会创建ComboBox.您提供了一个String,因此DefaultFieldGroupFieldFactory想要创建一个TextField.但是你提供了一个ComboBox.最后会抛出异常.

有了自己的工厂,它将起作用.
不要忘记setItemDataSource(bean)和commit()你的绑定器实际上将性别写入bean.

标签:java,vaadin7
来源: https://codeday.me/bug/20190517/1119953.html