Wicket: Internationalization for enums

There are various nice tutorials available on how you would add internationalization to enum values. Some of them seem outdated because using a class called EnumChoiceRenderer – which is packaged with Wicket now – makes it very easy to, e.g., display the translated values of enums with a drop down box.

Example

Let’s have a look at the following example. Say, we have got an enum Gender and want to displayed the German translation of the values using a DropDownChoice element.

public enum Gender { MALE, FEMALE; }

Adding the drop down choice to a component is easy and passing the EnumChoiceRenderer is all that’s needed to advise Wicket that the values should be translated via corresponding calls to getString().

this.add(
  new DropDownChoice<Gender>(
    "gender",
    Arrays.asList(Gender.values()),
    new EnumChoiceRenderer<Gender>(this)
  )
);

By default the above implementation of IChoiceRenderer uses the simple name of the enum’s class name appended by a dot and the value’s name. That said, it becomes trivial to translate the values of the enum, e.g., in our MyWebApplication_de.properties.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM
   "http://java.sun.com/dtd/properties.dtd">
<properties>
	<entry key="Gender.MALE">Männlich</entry>
	<entry key="Gender.FEMALE">Weiblich</entry>
</properties>

Collecting all the translations of the enums in a global file seems to be a good idea, thus making it easy to use them in different packages throughout the application. In this case MyWebApplication extends Wicket’s WebApplication.

Conclusion

Using Wicket to translate the values of enums and displaying them in a drop down box could not be much easier. In fact, the features that come with Wicket’s core allow you to reach your goal quickly and elegantly and it’s worth checking out all the functionality packaged in the core to use it’s full potential when needed.