Thursday, June 14, 2007

How to use Java 5 Enums as the model objects in a Wicket DropDownChoice

This kind of thing is easy to do in Wicket, but it doesn't hurt to show how it's done. I like to use Java 5 Enums wherever possible to enforce strict type checking. This is an example of how to use Java 5 Enums as the model objects in a Wicket DropDownChoice. It also illustrates how to localise the Enum values.

Tester.java


package com.my.pages;

import java.util.Arrays;
import java.util.List;

import wicket.markup.html.WebPage;
import wicket.markup.html.form.Button;
import wicket.markup.html.form.DropDownChoice;
import wicket.markup.html.form.Form;
import wicket.markup.html.form.IChoiceRenderer;
import wicket.model.PropertyModel;
import wicket.model.ResourceModel;

/**
* @author jsinai
*/
public class Tester extends WebPage
{
private enum GenerationMethod
{
AUTO, MANUAL
};
private GenerationMethod generationMethod = GenerationMethod.AUTO;

public Tester()
{
final List generationMethods = Arrays
.asList(new GenerationMethod[]
{ GenerationMethod.AUTO, GenerationMethod.MANUAL });

final DropDownChoice generationMethodCombo = new DropDownChoice(
"mycomboid", new PropertyModel(this, "generationMethod"),
generationMethods, new IChoiceRenderer()
{
public Object getDisplayValue(Object methodObj)
{
// Localize / Show user friendly strings
return getString(methodObj.toString());
}

public String getIdValue(Object id, int index)
{
return id.toString();
}
});


Button ok = new Button("mybuttonid", new ResourceModel("okbutton"))
{
@Override
protected void onSubmit()
{
GenerationMethod method = getGenerationMethod();
System.out.println("generationMethod = " + method);
}
};

Form form = new Form("myformid");
form.add(generationMethodCombo);
form.add(ok);
add(form);
}

public GenerationMethod getGenerationMethod()
{
return generationMethod;
}
public void setGenerationMethod(GenerationMethod generationMethod)
{
this.generationMethod = generationMethod;
}
}

Tester.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:wicket="http://wicket.sourceforge.net/" xml:lang="en"
lang="en">
<body>
<form wicket:id="myformid">
<select wicket:id="mycomboid">
</select>
<input type="submit" wicket:id="mybuttonid" />
</form>
</body>
</html>

Tester.properties


AUTO=Automatic
MANUAL=Manual
okbutton=OK

2 comments:

KJ said...

Great article. This is exactly what I was trying to do. Thanks!

summ3r said...

You should consider using this online tool for managing your software strings when localizing Java projects, if you want to save yourself some time: https://poeditor.com/