Say I have a drop-down menu in my java application. I used the below XML code to call the list of menus:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menutypes>
<Menutype>
<name>Menu A</name>
<type>2</type>
<param>0</param>
<diameter>0</diameter>
<autocollimatable>false</autocollimatable>
<autotrackable>false</autotrackable>
</Menutype>
<Menutype>
<name>Menu B</name>
<type>1</type>
<param>0</param>
<diameter>30</diameter>
<autocollimatable>true</autocollimatable>
<autotrackable>false</autotrackable>
</Menutype>
<Menutype>
<name>Menu C</name>
<type>0</type>
<param>-17</param>
<diameter>23</diameter>
<autocollimatable>true</autocollimatable>
<autotrackable>false</autotrackable>
</Menutype>
</menutypes>
Now I call the above menus in one of my java class like so; instance = JAXB.unmarshal(new FileInputStream("src/resource/menutypes.xml"), Menutypes.class);
. Now I want to implement localization for each corresponding menus based on the user's locale settings like one for Japanese and one for Chinese and so on so that when they open the app, it will show the language based on their locale. Is there any effective way to implement this in Java?
One possibility would be to have a ResourceBundle
that specifies that name of the XML file to use for each locale, and then get the filename from it. You would then have one XML file per locale.
MenuBundle_en_US.properties
filename=menutypes_en_US.xml
MenuBundle_jp_JP.properties
filename=menutypes_jp_JP.xml
MenuBundle_zh_CN.properties
filename=menutypes_zh_CN.xml
Menu.java
public Menutypes loadMenus(Locale locale) {
ResourceBundle bundle = ResourceBundle.getBundle("MenuBundle", locale);
String filename = bundle.getString("filename");
Menutypes instance = JAXB.unmarshal
new FileInputStream("src/resource/" + filename), Menutypes.class);
return instance;
}
Something like that, modulo error handling. I don't know if there's a better way to do it with XML.
Here is the sample.
public final class ResourceUtils {
private static final String MESSAGE_FILE_NAME = "messages";
public static String getMessage(String key) {
Locale local = SessionPreferences.getCurrentLocale();
ResourceBundle bundle = ResourceBundle.getBundle(MESSAGE_FILE_NAME, local);
return bundle.getString(key);
}
}
The file messages.properties
APP.title=HOME
APP.home.title=Salesman
Then you can modify the set/get:
class Menutypes {
String getName() {
return ResourceUtils.getMessage('APP.title');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.