我尝试在我的应用程序中使用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
我是怎么做到的?
答案 0 :(得分:6)
这是个好问题!经过一番调查后,我找到了以下解决方案:
您必须创建自定义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);
}
});
之所以:
如果你看一下DefaultFieldGroupFieldFactory.java的vaadin源代码,你会发现只有在你提供Enum as&#34;属性数据源时才会创建ComboBox
&# 34 ;.您提供了一个字符串,以便DefaultFieldGroupFieldFactory
想要创建TextField
。但是你提供了ComboBox
。最后会抛出异常。
拥有自己的工厂,它将起作用。
不要忘记setItemDataSource(bean)
和commit()
您的活页夹实际上将性别写入bean。