Java Examples In A Nutshell (3rd Edition) [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java Examples In A Nutshell (3rd Edition) [Electronic resources] - نسخه متنی

O'Reilly Media, Inc

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








8.5 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.


8.5.1 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, it is often
easier to subclass ListResourceBundle. You can
also simply provide a property file (see the
java.util.Properties class) that
ResourceBundle.getBundle( ) uses to create an
instance of PropertyResourceBundle.

To use
localized resources from a ResourceBundle in a
program, you should first call the static getBundle(
)
method, which dynamically loads and instantiates a
ResourceBundle, as described shortly. The returned
ResourceBundle has the name you specify and is
appropriate for the specified locale (or for the default locale if no
locale is explicitly specified). Once you have obtained a
ResourceBundle object with getBundle(
)
, use the getObject( ) method to look
up resources by name. Note that there is a convenience method,
getString( ), that simply casts the value returned
by getObject( ) to be a String
object.

When you call getBundle( ), you specify the base
name of the desired ResourceBundle and a desired
locale (if you don't want to rely on the default
locale). Recall that a Locale is specified with a
two-letter language code, an optional two-letter country code, and an
optional variant string. getBundle( ) looks for an
appropriate ResourceBundle class for the locale by
appending this locale information to the base name for the bundle.
The method looks for an appropriate class with the following
algorithm:

  1. Search for a class with the following name:

    basename_language_country_variant

    If no such class is found or no variant string is specified for the
    locale, it goes to the next step.

  2. Search for a class with the following name:

    basename_language_country

    If no such class is found or no country code is specified for the
    locale, it goes to the next step.

  3. Search for a class with the following name:

    basename_language

    If no such class is found, it goes to the final step.

  4. Search for a class that has the same name as the basename, or, in
    other words, search for a class with the following name:

    basename

    This represents a default resource bundle used by any locale that is
    not explicitly supported.


At each step in this process,
getBundle( ) checks first for a class file with
the given name. If no class file is found, it uses the
getResourceAsStream( ) method of
ClassLoader to look for a
Properties file with the same name as the class
and a .properties extension. If such a
properties file is found, its contents are used to create a
Properties object, and getBundle(
)
instantiates and returns a
PropertyResourceBundle that exports the properties
in the Properties file through the
ResourceBundle API.

If
getBundle( ) cannot find a class or properties
file for the specified locale in any of the four previous search
steps, it repeats the search using the default locale instead of the
specified locale. If no appropriate ResourceBundle
is found in this search either, getBundle( )
throws a MissingResourceException.

Any
ResourceBundle object can have a parent
ResourceBundle specified for it. When you look up
a named resource in a ResourceBundle,
getObject( ) first looks in the specified bundle,
but if the named resource is not defined in that bundle, it
recursively looks in the parent bundle. Thus, every
ResourceBundle inherits the resources of its
parent and may choose to override some, or all, of these resources.
(Note that we are using the terms
"inherit" and
"override" in a different sense
than we do when talking about classes that inherit and override
methods in their superclass.) What this means is that every
ResourceBundle you define does not have to define
every resource required by your application. For example, you might
define a ResourceBundle of messages to display to
French-speaking users. Then you might define a smaller and more
specialized ResourceBundle that overrides a few of
these messages so that they are appropriate for French-speaking users
who live in Canada.

Your application is not required to find and set up the parent
objects for the ResourceBundle objects it uses.
The getBundle( ) method actually does this for
you. When getBundle( ) finds an appropriate class
or properties file as described previously, it does not immediately
return the ResourceBundle it has found. Instead,
it continues through the remaining steps in the previous search
process, looking for less-specific class or properties files from
which the ResourceBundle may inherit resources. If
and when getBundle( ) finds these less-specific
resource bundles, it sets them up as the appropriate ancestors of the
original bundle. Only once it has checked all possibilities does it
return the original ResourceBundle object that it
created.

To continue the example begun earlier, when a program runs in Quebec,
getBundle( ) might first find a small specialized
ResourceBundle class that has only a few specific
Quebecois resources. Next, it looks for a more general
ResourceBundle that contains French messages, and
it sets this bundle as the parent of the original Quebecois bundle.
Finally, getBundle( ) looks for (and probably
finds) a class that defines a default set of resources, probably
written in English (assuming that English is the native tongue of the
original programmer). This default bundle is set as the parent of the
French bundle (which makes it the grandparent of the Quebecois
bundle). When the application looks up a named resource, the
Quebecois bundle is searched first. If the resource
isn't defined there, the French bundle is searched,
and any named resource not found in the French bundle is looked up in
the default bundle.


8.5.2 ResourceBundle Example


Examining some code makes this
discussion of resource bundles much clearer. Example 8-4 is a convenience routine for creating Swing
menu panes. Given a list of menu item names, it looks up labels and
menu shortcuts for those named menu items in a resource bundle and
creates a localized menu pane. The example has a simple test program
attached.

Figure 8-3 shows the menus it creates in the
American, British, and French locales. This program cannot run, of
course, without localized resource bundles from which the localized
menu labels are looked up.


Figure 8-3. Localized menu panes


Example 8-4. SimpleMenu.java

package je3.i18n;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
/** A convenience class to automatically create localized menu panes */
public class SimpleMenu {
/** The convenience method that creates menu panes */
public static JMenu create(ResourceBundle bundle,
String menuname, String[] itemnames,
ActionListener listener)
{
// Get the menu title from the bundle. Use name as default label.
String menulabel;
try { menulabel = bundle.getString(menuname + ".label"); }
catch(MissingResourceException e) { menulabel = menuname; }
// Create the menu pane.
JMenu menu = new JMenu(menulabel);
// For each named item in the menu.
for(int i = 0; i < itemnames.length; i++) {
// Look up the label for the item, using name as default.
String itemlabel;
try {
itemlabel =
bundle.getString(menuname+"."+itemnames[i]+".label");
}
catch (MissingResourceException e) { itemlabel = itemnames[i]; }
JMenuItem item = new JMenuItem(itemlabel);
// Look up an accelerator for the menu item
try {
String acceleratorText =
bundle.getString(menuname+"."+itemnames[i]+".accelerator
bundle.getString(menuname+"."+itemnames[i]+".accelerator");
item.setAccelerator(KeyStroke.getKeyStroke(acceleratorText));
}
catch (MissingResourceException e) {}
// Register an action listener and command for the item.
if (listener != null) {
item.addActionListener(listener);
item.setActionCommand(itemnames[i]);
}
// Add the item to the menu.
menu.add(item);
}
// Return the automatically created localized menu.
return menu;
}
/** A simple test program for the above code */
public static void main(String[] args) {
// Get the locale: default, or specified on command-line
Locale locale;
if (args.length == 2) locale = new Locale(args[0], args[1]);
else locale = Locale.getDefault( );
// Get the resource bundle for that Locale. This will throw an
// (unchecked) MissingResourceException if no bundle is found.
ResourceBundle bundle =
ResourceBundle.getBundle("com.davidflanagan.examples.i18n.Menus",
locale);
// Create a simple GUI window to display the menu with
final JFrame f = new JFrame("SimpleMenu: " + // Window title
locale.getDisplayName(Locale.getDefault( )));
JMenuBar menubar = new JMenuBar( ); // Create a menubar.
f.setJMenuBar(menubar); // Add menubar to window
// Define an action listener that our menu will use.
ActionListener listener = new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand( );
Component c = f.getContentPane( );
if (s.equals("red")) c.setBackground(Color.red);
else if (s.equals("green")) c.setBackground(Color.green);
else if (s.equals("blue")) c.setBackground(Color.blue);
}
};
// Now create a menu using our convenience routine with the resource
// bundle and action listener we've created
JMenu menu = SimpleMenu.create(bundle, "colors",
new String[] {"red", "green", "blue"},
listener);
// Finally add the menu to the GUI, and pop it up
menubar.add(menu); // Add the menu to the menubar
f.setSize(300, 150); // Set the window size.
f.setVisible(true); // Pop the window up.
}
}

As I've already said, this example does not stand
alone. It relies on resource bundles to localize the menu. The
following listing shows three property files that serve as resource
bundles for this example. Note that this single listing contains the
bodies of three separate files:

# The file Menus.properties is the default "Menus" resource bundle.
# As an American programmer, I made my own locale the default.
colors.label=Colors
colors.red.label=Red
colors.red.accelerator=alt R
colors.green.label=Green
colors.green.accelerator=alt G
colors.blue.label=Blue
colors.blue.accelerator=alt B
#This is the file Menus_en_GB.properties.It is the resource bundle for
# British English.
Note that it overrides only a single resource definition
# and simply inherits the rest from the default (American) bundle.
colors.label=Colours
#This is the file Menus_fr.properties.It is the resource bundle for all
# French-speaking locales. It overrides most, but not all,
of the resources
# in the default bundle.
colors.label=Couleurs
colors.red.label=Rouge
colors.green.label=Vert
colors.green.accelerator=control shift V
colors.blue.label=Bleu


/ 285