Internationalization in Java

Asked

Viewed 496 times

0

I am having some difficulty to carry out the internationalization of my java application.

My question is as follows: when I have a "login" screen, for example, and select the option in my Jmenuitem: "English", my entire application, my layout, should change according to the selected option, leaving it all in English. I’d like to know how to make that happen.

Follow my code of how I’m doing I’m trying to do:

  • 3

    To downvoters: it is good to comment on alternatives to improve the issue.

  • What kind of application? Is it made in swing? If yes, you need to change all the texts manually in a method to part.

  • And a desktop application and it is made with swing, I will change and put here as was my code.

  • Please post a code that is [mcve], so that it is possible to reproduce and test it.

1 answer

1

So you can do this using a language file. It would be something like:

1- Method to recover language file selected based on language option selected in Jmenuitem (files . lang would be in the lang folder of the project):

class Language {
private Properties language;
public void loadLanguage(int lang) throws FileNotFoundException,
        IOException {
    if (lang == 0)
        language = getLanguageProperties("lang/english.lang");
    else if (lang == 1)
        language = getLanguageProperties("lang/portuguese.lang");
}

protected Properties getLanguageProperties(String languageFile)
        throws FileNotFoundException, IOException {
    File file = new File(languageFile);
    Properties props = new Properties();
    props.load(new FileInputStream(file));
    return props;
}
}

2-Retrieve text from a component via its key:

class LanguageController {
    public static String getProperty(String key) {
       return language.getProperty(key);
    }
}

3-Loading text from application swing components:

JButton componente = new JButton();
componente.setText(
            LanguageController.getProperty(
                    "BOTAO_KEY")

4- The language file would contain the content with the key and value ("English.lang"):

BOTAO_KEY=Texto do meu button

If you’re curious, take a look at the project where I did this internationalization treatment: https://sourceforge.net/projects/j-syncker/. There is a language menu that allows the user to change the language at runtime. I hope to have helped ^^

  • Out of curiosity, I could show this applied in practice in a simple example?

  • That would be item 3 that has the example. It loads the jbutton text based on the language selected by default. If the user wants to change the language, just call the loadLanguage method.

  • And how this will be saved in the file?

  • Okay, I added now! Vlw by tip :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.