Localizing User-Visible Messages

The third task of internationalization involves ensuring that there are no user-visible strings that are hardcoded in an application; instead, strings should be looked up based on the locale. In Example 8-3, for example, the strings “Portfolio value”, “Symbol”, “Shares”, and others are hardcoded in the application and appear in English, even when the program is run in the French locale. The only way to prevent this is to fetch all user-visible messages at runtime and to translate every message into each language your application must support.

Java helps you handle this task with the ResourceBundle class of the java.util package. This class represents a bundle of resources that can be looked up by name. You define a localized resource bundle for each locale you want to support, and Java loads the correct bundle for the default (or specified) locale. With the correct bundle loaded, you can look up the resources (typically strings) your program needs at runtime.

Working with Resource Bundles

To define a bundle of localized resources, you create a subclass of ResourceBundle and provide definitions for the handleGetObject( ) and getKeys( ) methods. handleGetObject( ) is passed the name of a resource; it should return an appropriate localized version of that resource. getKeys( ) should return an Enumeration object that gives the user a list of all resource names defined in the ResourceBundle. Instead of subclassing ResourceBundle directly, however, ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.