How can I change the Language of the Program in Java code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • notfound
    New Member
    • Jun 2012
    • 28

    How can I change the Language of the Program in Java code?

    Hi everyone,
    In my Download Manager Java project, I put two options for the user to change the langauge (Turkish and English).My project is written according to MVC structure, so I have also view(User interface).I prepared JFrame and I put Options and Language item in it.Language extens to English and Turkish.When the user selects Turkish all the text in the program should be returned to Turkish.I made also some Google search and saw Resorcebundle examples, but I couldn't apply it to my project.How can write Java code to change the language?Thanks .
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    What did you try and where did you fail?

    Comment

    • chaarmann
      Recognized Expert Contributor
      • Nov 2007
      • 785

      #3
      Without showing some piece of code, and without giving any reasons why you couldn't apply resource bundles, I can give you general advice with an easier to understand, homebrew method:
      Use keys when you need to to print/assign the words in different languages.
      Put all your keys and its associated english words in a file "english.proper ties"
      For example:
      TURKEY=Turkey
      SELECTION_NEEDE D=Please select an item
      Put all your keys and its associated turkish words in a file "turkish.proper ties"
      TURKEY=Türkiye
      SELECTION_NEEDE D=...

      Then read this text into a property object:
      Code:
      Properties englishProperties = new Properties();
      englishProperties.load(new FileInputStream("english.properties"));
      Properties turkishProperties = new Properties();
      turkishProperties.load(new FileInputStream("turkish.properties"));
      Now, whenever you need a text in your program, don't hardcode it there, but read it from the properties. For example a language button:
      Code:
      public String getText(String language, String key) {
        if (language.equals("English")) {
          return englishProperties.getProperty(key);
        }
        if (language.equals("Turkish")) {
          return turkishProperties.getProperty(key);
        }
        return null;
      }
      ...
      String currentLanguage = ... // get the preferred language from the user
      myButton = ... // get the button GUI element
      myMessageScreen= ... // get the message screen GUI element
      myButton.setText(getText(currentLanguage, "TURKEY"));
      myMessageScreen.setText(getText(currentLanguage, "SELECTION_NEEDED"));
      This way, it is easy to implement more languages, like a german.properti es file.

      Improvements:
      - pass language as Enum, not as String
      - read properties from database, not from file (easier deployment, no problems with special characters etc.)

      Comment

      Working...