O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatted Messages

We've seen that in order to internationalize programs, you must place all user-visible messages into resource bundles. This is straightforward when the text to be localized consists of simple labels such as those on buttons and menu items. It is trickier, however, with messages that are composed partially of static text and partially of dynamic values. For example, a compiler might have to display a message such as "Error at line 5 of file "hello.java"", in which the line number and filename are dynamic and locale-independent, while the rest of the message is static and needs to be localized.

The MessageFormat class of the java.text package helps tremendously with these types of messages. To use it, you store only the static parts of a message in the ResourceBundle and include special characters that indicate where the dynamic parts of the message are to be placed. For example, one resource bundle might contain the message: "Error at line {0} of file {1}". And another resource bundle might contain a "translation" that looks like this: "Erreur: {1}: {0}".

To use such a localized message, you create a MessageFormat object from the static part of the message and then call its format( ) method, passing in an array of the values to be substituted. In this case, the array contains an Integer object that specifies the line number and a String object that specifies the filename. The MessageFormat class knows about other Format classes defined in java.text. It creates ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required