Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Creating a Button with I18N Resources

Problem

You want your program to take “sensitivity lessons” so it can communicate well internationally.

Solution

Your program must obtain all control and message strings via the internationalization software. Here’s how:

  1. Get a ResourceBundle.

    ResourceBundle b = ResourceBundle.getBundle("Menus");

    I’ll talk about ResourceBundle in Section 14.7, but briefly, a ResourceBundle represents a collection of name-value pairs (resources). The names are names you assign to each GUI control or other user interface text, and the values are the text to assign to each control in a given language.

  2. Use this ResourceBundle to fetch the localized version of each control name.

    Old way:

    somePanel.add(new JButton("Exit"));

    New way:

    rb = ResourceBundle.getBundle("Widgets");
    try { label = rb.getString("exit.label"); }
    catch (MissingResourceException e) { label="Exit"; } // fallback
    somePanel.add(new JButton(label));

    This is quite a bit of code for one button, but distributed over all the widgets (buttons, menus, etc.) in a program, it can be as little as one line with the use of convenience routines, which I’ll show in Section 14.4.

What happens at runtime?

The default locale is used, since we didn’t specify one. The default locale is platform-dependent:

  • Unix/POSIX: LANG environment variable (per user)

  • Windows 95: Start->Control Panel->Regional Settings

  • Others: see platform documentation

ResourceBundle.getBundle( ) locates a file with the named resource bundle name (Menus ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata