我遇到了一个Java Wicket表单的问题,其下拉选项如下:
public class SomePage extends WebPage {
public SomePage () {
CompoundPropertyModel<SomeBean> properties = new CompoundPropertyModel<SomeBean>(new SomeBean());
Form<SomeBean> form = new Form<SomeBean>("SomeBeanForm", properties) {
//override on submit
};
form.add(new DropDownChoice<MyEnum>("myEnum", Lists.newArrayList(MyEnum.values()));
add(form);
}
}
SomeBean很简单:
public class SomeBean {
private MyEnum myEnum;
// Getter, Setter
public SomeBean(){
}
}
而MyEnum是:
public enum MyEnum {
CHOICE1("1"),
CHOICE2("2");
private String id;
public MyEnum(String id) {
this.id=id;
}
//some methods to get/set/display id
}
我的问题是如何使用CompoundPropertyModel在bean中设置枚举?我得到一个例外:
Could not convert value: CHOICE1 to type: MyEnum Could not find compatible converter.
这是由于它不知道如何将任何内容转换为MyEnum对象,它需要一个易于创建的转换器,但是如何为CompoundPropertyModel创建的PropertyModel设置转换器呢?
感谢您的帮助!
- 编辑 -
这是枚举的错误导入,bean和dropdownchoice使用了具有相同名称的不同枚举。这段代码有效。
答案 0 :(得分:1)
您的代码不包含实体名称作为组件ID,这是使用CompoundPropertyModel的原因。
请参阅https://repo.twinstone.org/projects/WISTF/repos/wicket-examples-6.x/browse
上的完整代码示例HTML代码段
<form wicket:id="form">
<label>Text</label>: <input type="text" wicket:id="text" /> <br/>
<select wicket:id="choice"></select>
<input wicket:id="submit" type="submit" value="Send" />
</form>
CODE代码段
final IChoiceRenderer<ChoiceEnum> CHOICE_RENDERER = new ChoiceRenderer<ChoiceEnum>("description");
inal List<ChoiceEnum> ALL_CHOICES = Arrays.asList(ChoiceEnum.values());
final IModel<TextAndEnumBean> model = Model.of(new TextAndEnumBean());
final IModel<TextAndEnumBean> compoundModel = CompoundPropertyModel.of(model);
Form<TextAndEnumBean> form = new Form<>("form", compoundModel);
add(form);
form.add(new TextField<String>("text"));
form.add(new DropDownChoice<ChoiceEnum>("choice", ALL_CHOICES, CHOICE_RENDERER).setNullValid(true));
form.add(new Button("submit"));
实体Bean代码:
public class TextAndEnumBean implements Serializable {
private static final long serialVersionUID = 1L;
private String text;
private ChoiceEnum choice;
public TextAndEnumBean() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public ChoiceEnum getChoice() {
return choice;
}
public void setChoice(ChoiceEnum choice) {
this.choice = choice;
}
}
枚举定义代码:
public enum ChoiceEnum {
CHOICE1("choice no. 1"),
CHOICE2("choice no. 2"),
MY_CHOICE("example of my choice"),
ANTOHER_CHOICE("another choice");
private final String description;
private ChoiceEnum(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
答案 1 :(得分:0)
这应该可行:默认情况下,DropDownChoice将使用索引来标识所选的枚举值。那里没有转换。