Localizing enums with Seam
Posted March 26, 2008
on:- In: Codevaganza | Java
- 3 Comments
Wow, I just realized that I haven’t wrote anything in this blog for more than a month. Shame on me. Ok here’s another code that hopefully be beneficial. Recently I had a project where I need to display the enum values in local language. Thanks God for Seam I can easily do this.
In your model class (e.g Person.java)
public class Person { public enum Gender { MALE, FEMALE; @Override public String toString() { switch (this){ case MALE: return ResourceBundle.instance().getString("male"); case FEMALE: return ResourceBundle.instance().getString("female"); default: return super.toString(); } } private Gender gender; public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } };
I had this inner enum inside a Person class and in there I just override toString()
method. Inside the method I just call the Seam’s ResourceBundle component and call the appropriate message from my resource bundles which is located in messages.properties.Now when I call the gender property from my view, it will be automatically localized.
<h:panelGrid columns="2" columnClasses="form-column" rowClasses="form-row" styleClass="form-table"> <h:outputLabel for="gender" value="#{messages['gender']}" /> <h:outputText id="gender" value="#{client.gender}" /> </h:panelGrid>
3 Responses to "Localizing enums with Seam"
This is going to work but it’s not very elegant. You mix intenralization logic with your code. Better approach would be defining Gender like this (hope this form would accept tabs in code):
public enum Gender { MALE ( "key.for.male") , FEMALE ( "key.for.female" ); Gender( String key ) { this.key = key; } public String getKey() { return key; } }
and displaying it in jsf like this:
<h:outputText id=”gender” value=”#{messages[client.gender.key]}”/>
1 | agungfirmansyah
April 5, 2008 at 1:28 pm
Bos…, yang gambar kedua itu maksudnya apa? Itu pake bahasa apa sih?
tengs…