Complete Example of Internationalization in Java

In this section, we apply the material of this chapter to localize a retirement calculator. The program calculates whether or not you are saving enough money for your retirement. You enter your age, how much money you save every month, and so on (see Figure 7.4).

The text area and the graph show the balance of the retirement account for every year. If the numbers turn negative toward the later part of your life and the bars in the graph appear below the x axis, you need to do something—for example, save more money, postpone your retirement, die earlier, or be younger.

The retirement calculator works in three locales (English, German, and Chinese). Here are some of the highlights of the internationalization: [1]

  • The labels, buttons, and messages are translated into German and Chinese. You can find them in the classes RetireResources_de and RetireResources_zh. English is used as the fallback—see the RetireResources file.
  • Whenever the locale changes, we reset the labels and reformat the contents of the text fields.
  • The text fields handle numbers, currency amounts, and percentages in the local format.
  • The computation field uses a MessageFormat. The format string is stored in the resource bundle of each language.
  • Just to show that it can be done, we use different colors for the bar graph, depending on the language chosen by the user.

Listings 7.5 through 7.8 show the code. Listings 7.9 through 7.11 are the property files for the localized strings. Figures 7.5 and 7.6 show the outputs in German and Chinese, respectively. To see Chinese characters, be sure you have Chinese fonts installed and configured with your Java runtime. Otherwise, Chinese characters will show up as “missing character” icons.

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *