2012-08-02 53 views
0

Im有一些DropDownChoice问题。 我有一个枚举与学校的标题像列表:Wicket - 从Enum到DropHownChoice原始码

public enum StudyTitle { 

    NONE(null,null),ELEMENTARY("1","Elementary"),COLLEGE("2","College"); 

    private String code; 
    private String description; 

    private StudyTitle(String code, String description){ 
     setCode(code); 
     setDescription(description); 
    } 

    [setter and getter] 

} 

然后,我有一个POJO和String proprerty叫“studyTitleCode”我想要把代码(例如1所小学,2大学等...)。

当我创建一个DropDownChoice Wicket不允许我有一个类型为String的proprerty模型,如果DropDownChoice属于StudyTitle类型的话。

Ex。 [建设listOfStudyTitle作为枚举的ArrayList]

DropDownChoice<String> studyLevel = new DropDownChoice<String>("id",new PropertyModel<String>(myPojo,"studyTitleCode"),listOfStudyTitle,new ChoiceRenderer<StudyTitle>("description","code")); 

有没有一种方法,使检票的枚举的一个属性链接到模型的房产吗?

感谢

回答

1

选择选项的AbstractSingleSelectChoice必须在价值模型的类型相匹配。我知道的DropDownChoice的唯一相关配置选项是IChoiceRenderer,它允许您设置如何呈现枚举值(与默认调用toString())。

一个办法是,而是采用枚举实例本身为您选择的模式,给枚举可以使用String属性:

public enum TestEnum { 
    ONE ("ONE"), 
    TWO ("TWO"), 
    THREE ("THREE"); 

    private String value; 

    TestEnum(String value) { 
     this.value = value; 
    } 

    public String getValue() { 
     return value; 
    } 

    public static List<String> getStringValues() 
    { 
     List<String> stringValues = new ArrayList<String>(); 
     for (TestEnum test : values()) { 
      stringValues.add(test.getValue()); 
     } 

     return stringValues; 
    } 
} 

@Override 
protected void onInitialize() { 
    super.onInitialize(); 

    IModel<String> myStringValueModel = new Model<String>(); 
    add(new DropDownChoice<String>("id", myStringValueModel, TestEnum.getStringValues())); 
} 
+0

您的解决方案是好的,但我希望得到的字符串是不同的从我想要显示的字符串。 与我的枚举,我希望用户看到“描述”属性,但我想“代码”作为模型内的值。 – MrMime 2012-08-02 11:49:04

+2

如果您需要将模型的值更改为某个显示值,则可以使用DropDownChoice#setChoiceRenderer(IChoiceRenderer)。 IChoiceRenderer有一个抽象方法getDisplayValue(T),它只接受模型参数。从那里,查询你的枚举显示值... – 2012-08-03 01:42:45