Java Reference
In-Depth Information
Example 7−3: Portfolio.java (continued)
}
}
Setting the Locale
Example 7-3 contains code that explicitly sets the locale using the language code
and the country code specified on the command line. If these arguments are not
specified, it uses the default locale for your system. When experimenting with
internationalization, you may want to change the default locale for the entire plat-
form, so you can see what happens. How you do this is platform-dependent. On
Unix platforms, you typically set the locale by setting the LANG environment vari-
able. For example, to set the locale for Canadian French, using a Unix csh -style
shell, use this command:
% setenv LANG fr_CA
Or, to set the locale to English as spoken in Great Britain when using a Unix sh -
style shell, use this command:
$ export LANG=en_GB
To set the locale in Windows, use the Regional Settings control on the Windows
Control Panel.
Localizing User-Visible Messages
The third task of internationalization involves ensuring that there are no user-visi-
ble strings that are hardcoded in an application; instead, strings should be looked
up based on the locale. In Example 7-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 pre-
vent this is to fetch all user-visible messages at runtime and to translate every mes-
sage into each languages 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 pro-
gram needs at runtime.
Working with Resource Bundles
To define a bundle of localized resources, you create a subclass of ResourceBun-
dle and provide definitions for the handleGetObject() and getKeys() methods.
handleGetObject() is passed the name of a resource; it should return an appropri-
ate localized version of that resource. getKeys() should returnan Enumeration
object that gives the user a list of all resource names defined in the ResourceBun-
dle . Instead of subclassing ResourceBundle directly, however, it is often easier to
Search WWH ::




Custom Search