当前页面: 开发资料首页 → Java 专题 → Java中的国际化,第二部分
摘要: 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.
}
# 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
package je3.i18n;
import java.text.*;
import java.io.*;
import java.util.*;
/**
* A convenience class that can display a localized exception message
* depending on the class of the exception. It uses a MessageFormat,
* and passes five arguments that the localized message may include:
* {0}: the message included in the exception or error.
* {1}: the full class name of the exception or error.
* {2}: the file the exception occurred in
* {3}: a line number in that file.
* {4}: the current date and time.
* Messages are looked up in a ResourceBundle with the basename
* "Errors", using a the full class name of the exception object as
* the resource name. If no resource is found for a given exception
* class, the superclasses are checked.
**/
public class LocalizedError {
public static void display(Throwable error) {
ResourceBundle bundle;
// Try to get the resource bundle.
// If none, print the error in a nonlocalized way.
try {
String bundleName = "com.davidflanagan.examples.i18n.Errors";
bundle = ResourceBundle.getBundle(bundleName);
}
catch (MissingResourceException e) {
error.printStackTrace(System.err);
return;
}
// Look up a localized message resource in that bundle, using the
// classname of the error (or its superclasses) as the resource name.
// If no resource was found, display the error without localization.
String message = null;
Class c = error.getClass( );
while((message == null) && (c != Object.class)) {
try { message = bundle.getString(c.getName( )); }
catch (MissingResourceException e) { c = c.getSuperclass( ); }
}
if (message == null) { error.printStackTrace(System.err); return; }
// Get the filename and linenumber for the exception
// In Java 1.4, this is easy, but in prior releases, we had to try
// parsing the output Throwable.printStackTrace( );
StackTraceElement frame = error.getStackTrace( )[0]; // Java 1.4
String filename = frame.getFileName( );
int linenum = frame.getLineNumber( );
// Set up an array of arguments to use with the message
String errmsg = error.getMessage( );
Object[ ] args = {
((errmsg!= null)?errmsg:""), error.getClass( ).getName( ),
filename, new Integer(linenum), new Date( )
};
// Finally, display the localized error message, using
// MessageFormat.format( ) to substitute the arguments into the message.
System.err.println(MessageFormat.format(message, args));
}
/**
* This is a simple test program that demonstrates the display( ) method.
* You can use it to generate and display a FileNotFoundException or an
* ArrayIndexOutOfBoundsException
**/
public static void main(String[ ] args) {
try { FileReader in = new FileReader(args[0]); }
catch(Exception e) { LocalizedError.display(e); }
}
}
#
# This is the file Errors.properties
# One property for each class of exceptions that our program might
# report. Note the use of backslashes to continue long lines onto the
# next. Also note the use of \n and \t for newlines and tabs
#
java.io.FileNotFoundException: \
Error: File "{0}" not found\n\t\
Error occurred at line {3} of file "{2}"\n\tat {4}
java.io.UnsupportedEncodingException: \
Error: Specified encoding not supported\n\t\
Error occurred at line {3} of file "{2}"\n\tat {4,time} on {4,date}
java.io.CharConversionException:\
Error: Character conversion failure. Input data is not in specified format.
# A generic resource. Display a message for any error or exception that
# is not handled by a more specific resource.
java.lang.Throwable:\
Error: {1}: {0}\n\t\
Error occurred at line {3} of file "{2}"\n\t{4,time,long} {4,date,long}
colors.label=颜色设置
colors.red.label=红色
colors.red.accelerator=alt R
colors.green.label=绿色
colors.green.accelerator=alt G
colors.blue.label=蓝色
colors.blue.accelerator=alt B
/**Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd 编者按:使你的Java程序能在本地小镇甚至飘洋过海都运行良好,这面临诸多的挑战.我们已经在<
* @todo传入一个以UTF-8编码的字符,输出UTF-16编码的中文
* @ param inputStr String 需要转换的字串
*/
public static String getChineseOut(String inputStr){
try{
String temp_s = inputStr;
byte[] temp_b = null;
temp_b = temp_s.getBytes("ISO8859-1");
String result = new String(temp_b);
return result;
}
catch(Exception e){
e.printStackTrace();
return inputStr;
}
}