I needed a drop-down in Wicket which allowed the user to select their language to update the app/site content. I also wanted the languages to appear in their own character sets as well. Something that looks like this...
Java and the Locale class can provide us with this quite easily so here is a simple component based on the standard Wicket DropDownChoice component that does the job. You pass it a bunch of Locale objects representing the languages that you want to be supported and it will update the model you give it when it's selected...
/**
* Wicket Drop-down language / locale selector
*
* @author Eurig Jones
*/
public class DropDownLocale extends DropDownChoice<Locale>
{
public DropDownLocale(String id, IModel<Locale> model, List locales)
{
super(id, model, locales);
setChoiceRenderer(new LocaleChoiceRenderer());
}
@Override
protected void onSelectionChanged(Locale newSelection)
{
getSession().setLocale(newSelection);
}
@Override
protected boolean wantOnSelectionChangedNotifications()
{
return true;
}
private class LocaleChoiceRenderer implements IChoiceRenderer<Locale>
{
@Override
public Object getDisplayValue(Locale locale)
{
// Change this to just locale.getDisplayLanguage() and it'll display the languages in the currently selected language / Locale and character set.
return locale.getDisplayLanguage(locale);
}
@Override
public String getIdValue(Locale locale, int i)
{
return locale.getLanguage();
}
}
}
Some markup...
<select wicket:id="selectLanguage"></select>
Here is some example calling code. We pass our new DropDownLocale component a bunch of Locale objects representing the languages we intend to support. We also pass it a model to update. Here I have chosen to directly modify the session using a PropertyModel so as soon as the drop-down is used, the app is updated with the correct language...
List<Locale> supportedLanguages = new ArrayList<Locale>();
supportedLanguages.add(Locale.ENGLISH);
supportedLanguages.add(Locale.FRENCH);
supportedLanguages.add(Locale.JAPANESE);
PropertyModel<Locale> model = new PropertyModel<Locale>(getSession(), "locale");
DropDownLocale selectLanguage = new DropDownLocale("selectLanguage", model, supportedLanguages);
add(selectLanguage);