在 Java 中创建 locale -object 的正确方法是什么(例如芬兰语)

Sam*_*ami 1 java locale localization facescontext jsf-2

有人能告诉我为什么语言环境芬兰语不起作用而其余的?

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());

              }
               }

        }
Run Code Online (Sandbox Code Playgroud)

我的意思是我用 New-clause 创建的语言环境不起作用。我无法更好地解释它,因为我认为这样实现的语言环境与例如 Locale.GERMAN 的语言环境对象类似?我的软件除了更新语言环境 ja Faces 上下文之外什么都不做。没有例外。对不起,如果 q 是愚蠢的。其他一切都在工作,我的意思是德语、英语等,程序会更新语言环境和面孔上下文。

如果您回答这个问题,我将不胜感激,我(再次)迷路了萨米

Bal*_*usC 6

你的updateLocale()方法似乎是罪魁祸首。你在Locale#toString()newLocale. 该Locale常数都只有语言集,而不是国家。Locale.ENGLISH.toString()例如返回"en"new Locale("fi", "FI").toString()返回"fi_FI"。这只能说明你的newLocale变量实际上包含"en""fr""de""fi"。前三个将匹配常量,但后者将不匹配finnishLocale,因为您正在与其比较toString()而不是getLanguage()

要解决你的问题,要么改变

private static Locale finnishLocale = new Locale("fi", "FI");
Run Code Online (Sandbox Code Playgroud)

private static Locale finnishLocale = new Locale("fi");
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,更改Map<String, Object>Map<String, Locale>然后更改

if(entry.getValue().toString().equals(newLocaleValue)){
Run Code Online (Sandbox Code Playgroud)

if(entry.getValue().getLanguage().equals(newLocaleValue)){
Run Code Online (Sandbox Code Playgroud)

总之,这个地图循环相当笨拙。如果newLocale是服务器端控制的值,请viewRoot.setLocale(new Locale(newLocale))改为执行。