[英]What is the correct way to create locale -object in Java (for instance Finnish)
有人可以告诉我为什么芬兰语区域设置不起作用,而其余的却起作用吗?
private static Map<String,Object> countries;
private static Locale finnishLocale = new Locale("fi", "FI");
static{
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH); //label, value
countries.put("French", Locale.FRENCH);
countries.put("German", Locale.GERMAN);
countries.put("Finnish", finnishLocale); <---------- Not working!
}
public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
updateLocale(localeCode);
}
public void updateLocale(String newLocale){
String newLocaleValue = newLocale;
//loop country map to compare the locale code
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if(entry.getValue().toString().equals(newLocaleValue)){
FacesContext.getCurrentInstance()
.getViewRoot().setLocale((Locale)entry.getValue());
}
}
}
我的意思是我用新条款创建的语言环境不起作用。 我无法更好地解释它,因为我认为像这样实现的语言环境与Locale.GERMAN这样的语言环境对象是相似的? 除了更新区域设置ja Faces上下文外,我的软件没有任何其他作用。 没有例外。 对不起,如果q是愚蠢的。 其他所有内容均正常运行,我的意思是德语,英语等,并且程序会更新语言环境和Faces上下文。
如果您回答这个问题,我会很感激,我迷失了(再次)萨米
您的updateLocale()
方法似乎是罪魁祸首。 您正在将Locale#toString()
与newLocale
进行比较。 Locale
常量仅具有所有语言集,而没有国家/地区。 例如, Locale.ENGLISH.toString()
返回"en"
而new Locale("fi", "FI").toString()
返回"fi_FI"
。 那只能意味着您的newLocale
变量实际上包含"en"
, "fr"
, "de"
和"fi"
。 前三个将匹配常量,但后一个将不匹配finnishLocale
,因为您要与其getLanguage()
toString()
而不是getLanguage()
。
要解决你的问题, 要么改变
private static Locale finnishLocale = new Locale("fi", "FI");
至
private static Locale finnishLocale = new Locale("fi");
或者 ,最好将Map<String, Object>
更改为Map<String, Locale>
,然后更改
if(entry.getValue().toString().equals(newLocaleValue)){
至
if(entry.getValue().getLanguage().equals(newLocaleValue)){
总而言之,这个映射循环相当笨拙。 如果newLocale
是服务器端控制的值,则只需执行viewRoot.setLocale(new Locale(newLocale))
。
由于这可行,您在其他地方有一个错误:
public class Runner01 {
private static Map<String,Object> countries;
private static Locale finnishLocale = new Locale("fi", "FI");
static{
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH); //label, value
countries.put("French", Locale.FRENCH);
countries.put("German", Locale.GERMAN);
countries.put("Finnish", finnishLocale);
}
public static void main(String[] args) {
for( Map.Entry<String, Object> entry : countries.entrySet() ) {
System.out.println(entry.getKey() + "=>" + entry.getValue().toString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.