Wicket ChoiceRenderer for Enums
January 10th, 2008 by Michael Sparer | Published in Wicket
I now got to the point where I wanted to put some i18n into my DropDownChoices. What I found out pretty soon was that you need an IChoiceRenderer to customise your DropDownChoices. If you don’t use one, you’ll get by default short values and toString display names. E.g. the enum
enum { JOHN, PAUL, GEORGE, RINGO }
produces an output like that
<select name="beatles">
<option value="0">JOHN</option>
<option value="1">PAUL</option>
<option value="2">GEORGE</option>
<option value="3">RINGO</option>
</select>
But what I want is “John” instead of JOHN or “John Lennon, Rhythm Guitar” or anything but JOHN. On the mailinglist and in the wiki I discovered some complicated, overhead solutions using helper objects, so I decided to implement my own reusable enum-renderer that reads the display values from a properties file. All you have to do is to pass the Component that is responsible for the properties file.
public class EnumChoiceRenderer implements IChoiceRenderer {
private static final long serialVersionUID = 1L;
private final Component _resourceProvider;
public EnumChoiceRenderer(final Component resourceProvider) {
_resourceProvider = resourceProvider;
}
public Object getDisplayValue(final Object object) {
final Enum<?> v = (Enum<?>) object;
return _resourceProvider.getString(v.name());
}
public String getIdValue(final Object object, final int index) {
return Integer.toString(index);
}
}
Yeah that was quite easy, but maybe saves some of you the burdon of using helper-classes
Oh yes, the properties file looks something like that:
JOHN=John Lennon, Rhythm Guitar
PAUL=Paul McCartney, Bass
GEORGE=George Harrison, Lead Guitar
RINGO=Ringo Starr, Drums
what then produces the desired output:
<select name="beatles">
<option value="0">John Lennon, Rhythm Guitar</option>
<option value="1">Paul McCartney, Bass</option>
<option value="2">George Harrison, Lead Guitar</option>
<option value="3">Ringo Starr, Drums</option>
</select>