清單四:
cmdRed.setText(bundle.getString("red.label"));
cmdBlue.setText (bundle.getString("blue.label"));
cmdGreen.setText (bundle.getString("green.label"));
清單二中的cmdRed、cmdBlue、cmdGreen 為按鈕。bundle.getString("red.label")為得到資源文件中主鍵是red.label的值。
好了到此為止Java程序用戶界麵的本地化就是這麼簡單。不過,要提醒你的是在為用戶界麵事件編寫事件監聽器代碼時,要格外小心。請看下麵這段代碼。
清單五:
public class MyApplet extends Japplet implements ActionListener{
public void init(){
JButton cancelButton=new JButton(“Cancel”);
CancelButton.addActionListener(this);
...
}
public void actionPerformed(ActionEvent e){
String s=e.getActionCommand();
if(arg.equals(“Cancel”);
doCancel();
else ……
)
}
如果你對清單五的代碼不進行本地化,她就可能會運行的很好。但當你的按鈕被本地化為中文時,“Cancel”變為了“取消”。這時就會出現你不願意看到的問題。下麵有三個方法可以消除這個潛在的問題!
1> 使用內部類而不使用獨立的actionPerformed程序。
2> 使用引號而不使用標簽來標識組件。
3> 使用name屬性來標識組件
本例稍後的代碼就是采用第一種方法來消除這個問題的。
清單六:完整的代碼
//:MyNative.java
/**
Copyright (c) 2003 Dorian. All rights reserved
@(#)MyNative.java 2003-12-21
@author Dorian
@version 1.0.0
visit http://www.Dorian.com/Java/
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
這是一個將Java程序界麵地方化的例子本例采用讀取屬性文件來達到目的
@see java.util.Locale;
@see java.util.ResourceBundle;
@see java.util.MissingResourceException;
*/
public class MyNative{
public static void main(String[] args){
JFrame frame = new MyNativeFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true); // Pop the window up.
}
}
class MyNativeFrame extends JFrame{
public MyNativeFrame(){
Locale locale = Locale.getDefault();//獲取地區:默認
//獲取資源束。如未發現則會拋出MissingResourceException異常
//"Properties.Dorian"為在Properties下以Dorian為文件名的默認屬性文件
ResourceBundle bundle = ResourceBundle.getBundle("Properties.Dorian",locale);
setTitle(bundle.getString("Title"));//通過getString()的返回值來設置Title
setSize(WIDTH,HEIGHT); // Set the window size.
panel=new MyNativePanel();