本文目录导读:

我将为您提供一个完整的Java国际化(i18n)实现案例,包括配置、代码和演示。
项目结构
src/
├── main/
│ ├── java/
│ │ └── com/example/i18n/
│ │ ├── Main.java
│ │ ├── I18nManager.java
│ │ └── FormApp.java
│ └── resources/
│ └── messages/
│ ├── messages.properties (默认英文)
│ ├── messages_zh_CN.properties (简体中文)
│ ├── messages_ja_JP.properties (日文)
│ └── messages_fr_FR.properties (法文)
资源文件配置
messages.properties (默认英文)
app.welcome=Welcome to our application
app.greeting=Hello, {0}!
app.date=Current date: {0}
app.money=Total amount: {0}
app.exit=Exit
app.save=Save
app.cancel=Cancel
app.delete=Delete
app.confirm=Are you sure?
app.language=Select Language
menu.file=File
menu.edit=Edit
menu.help=Help
message.success=Operation completed successfully
message.error=An error occurred: {0}
messages_zh_CN.properties (中文)
app.welcome=欢迎使用我们的应用程序
app.greeting=你好,{0}!
app.date=当前日期:{0}
app.money=总金额:{0}
app.exit=退出
app.save=保存
app.cancel=取消
app.delete=删除
app.confirm=您确定吗?
app.language=选择语言
menu.file=文件
menu.edit=编辑
menu.help=帮助
message.success=操作成功完成
message.error=发生错误:{0}
messages_ja_JP.properties (日文)
app.welcome=アプリケーションへようこそ
app.greeting=こんにちは、{0}!
app.date=現在の日付:{0}
app.money=合計金額:{0}
app.exit=終了
app.save=保存
app.cancel=キャンセル
app.delete=削除
app.confirm=よろしいですか?
app.language=言語を選択
menu.file=ファイル
menu.edit=編集
menu.help=ヘルプ
message.success=操作が正常に完了しました
message.error=エラーが発生しました:{0}
messages_fr_FR.properties (法文)
app.welcome=Bienvenue dans notre application
app.greeting=Bonjour, {0} !
app.date=Date actuelle : {0}
app.money=Montant total : {0}
app.exit=Quitter
app.save=Enregistrer
app.cancel=Annuler
app.delete=Supprimer
app.confirm=Êtes-vous sûr ?
app.language=Sélectionnez la langue
menu.file=Fichier
menu.edit=Modifier
menu.help=Aide
message.success=Opération terminée avec succès
message.error=Une erreur s'est produite : {0}
国际化管理器类
package com.example.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* 国际化管理器
*/
public class I18nManager {
private static I18nManager instance;
private ResourceBundle bundle;
private Locale currentLocale;
private static final String BASE_NAME = "messages.messages";
private I18nManager() {
// 默认使用系统区域设置
currentLocale = Locale.getDefault();
loadBundle();
}
public static synchronized I18nManager getInstance() {
if (instance == null) {
instance = new I18nManager();
}
return instance;
}
/**
* 加载资源包
*/
private void loadBundle() {
try {
bundle = ResourceBundle.getBundle(BASE_NAME, currentLocale);
} catch (Exception e) {
// 如果加载失败,回退到默认区域
currentLocale = Locale.ENGLISH;
bundle = ResourceBundle.getBundle(BASE_NAME, Locale.ENGLISH);
}
}
/**
* 获取本地化字符串
*/
public String getMessage(String key) {
try {
return bundle.getString(key);
} catch (Exception e) {
return "???" + key + "???";
}
}
/**
* 获取带参数的本地化字符串
*/
public String getMessage(String key, Object... args) {
String pattern = getMessage(key);
if (args != null && args.length > 0) {
MessageFormat formatter = new MessageFormat(pattern, currentLocale);
return formatter.format(args);
}
return pattern;
}
/**
* 切换语言
*/
public void setLocale(Locale locale) {
currentLocale = locale;
loadBundle();
}
/**
* 获取当前区域
*/
public Locale getCurrentLocale() {
return currentLocale;
}
/**
* 获取所有支持的语言
*/
public static Locale[] getSupportedLocales() {
return new Locale[] {
Locale.ENGLISH,
Locale.SIMPLIFIED_CHINESE,
Locale.JAPANESE,
Locale.FRENCH
};
}
}
图形界面示例
package com.example.i18n;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 国际化GUI示例
*/
public class FormApp extends JFrame {
private I18nManager i18n;
private JLabel titleLabel;
private JLabel welcomeLabel;
private JLabel dateLabel;
private JLabel moneyLabel;
private JButton saveButton;
private JButton deleteButton;
private JButton cancelButton;
private JComboBox<String> languageBox;
private JTextField nameField;
private JTextArea outputArea;
public FormApp() {
i18n = I18nManager.getInstance();
initUI();
updateUI();
}
private void initUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
setLocationRelativeTo(null);
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 顶部 - 语言选择
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JLabel langLabel = new JLabel("Language:");
String[] languages = {"English", "简体中文", "日本語", "Français"};
languageBox = new JComboBox<>(languages);
languageBox.addActionListener(this::languageChanged);
topPanel.add(langLabel);
topPanel.add(languageBox);
// 中部 - 信息面板
JPanel infoPanel = new JPanel(new GridLayout(3, 1, 5, 5));
titleLabel = new JLabel();
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 16f));
welcomeLabel = new JLabel();
dateLabel = new JLabel();
moneyLabel = new JLabel();
infoPanel.add(titleLabel);
infoPanel.add(welcomeLabel);
infoPanel.add(dateLabel);
infoPanel.add(moneyLabel);
// 输入区域
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(15);
inputPanel.add(nameLabel);
inputPanel.add(nameField);
// 按钮区域
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
saveButton = new JButton();
deleteButton = new JButton();
cancelButton = new JButton();
saveButton.addActionListener(e -> handleSave());
deleteButton.addActionListener(e -> handleDelete());
cancelButton.addActionListener(e -> handleCancel());
buttonPanel.add(saveButton);
buttonPanel.add(deleteButton);
buttonPanel.add(cancelButton);
// 输出区域
outputArea = new JTextArea(8, 40);
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
// 组装布局
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(infoPanel, BorderLayout.NORTH);
centerPanel.add(inputPanel, BorderLayout.CENTER);
centerPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(scrollPane, BorderLayout.SOUTH);
add(mainPanel);
}
/**
* 更新所有UI文本
*/
private void updateUI() {
// 更新窗口标题
setTitle(i18n.getMessage("app.title"));
// 更新标签文本
titleLabel.setText(i18n.getMessage("app.title"));
welcomeLabel.setText(i18n.getMessage("app.welcome"));
// 格式化日期
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, i18n.getCurrentLocale());
String dateStr = dateFormat.format(new Date());
dateLabel.setText(i18n.getMessage("app.date", dateStr));
// 格式化金额(欧元示例)
String money = String.format("€1,234.56");
moneyLabel.setText(i18n.getMessage("app.money", money));
// 更新按钮文本
saveButton.setText(i18n.getMessage("app.save"));
deleteButton.setText(i18n.getMessage("app.delete"));
cancelButton.setText(i18n.getMessage("app.cancel"));
// 更新输出区域
updateOutput();
}
/**
* 语言切换事件
*/
private void languageChanged(ActionEvent e) {
int selectedIndex = languageBox.getSelectedIndex();
Locale[] locales = I18nManager.getSupportedLocales();
if (selectedIndex >= 0 && selectedIndex < locales.length) {
i18n.setLocale(locales[selectedIndex]);
updateUI();
}
}
/**
* 更新输出区域
*/
private void updateOutput() {
StringBuilder sb = new StringBuilder();
sb.append("=== i18n Messages ===\n");
sb.append("Current Locale: ").append(i18n.getCurrentLocale().getDisplayName()).append("\n");
sb.append("Language: ").append(i18n.getCurrentLocale().getLanguage()).append("\n");
sb.append("Country: ").append(i18n.getCurrentLocale().getCountry()).append("\n\n");
sb.append("Messages:\n");
String[] keys = {"app.title", "app.welcome", "app.greeting", "app.date", "app.money"};
for (String key : keys) {
sb.append(key).append(" => ").append(i18n.getMessage(key)).append("\n");
}
outputArea.setText(sb.toString());
}
private void handleSave() {
String name = nameField.getText().trim();
String message = i18n.getMessage("app.greeting", name.isEmpty() ? "Guest" : name);
JOptionPane.showMessageDialog(this,
i18n.getMessage("message.success") + "\n" + message,
i18n.getMessage("app.title"),
JOptionPane.INFORMATION_MESSAGE);
}
private void handleDelete() {
int result = JOptionPane.showConfirmDialog(this,
i18n.getMessage("app.confirm"),
i18n.getMessage("app.delete"),
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(this, i18n.getMessage("message.success"));
}
}
private void handleCancel() {
int result = JOptionPane.showConfirmDialog(this,
i18n.getMessage("app.confirm"),
i18n.getMessage("app.cancel"),
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
dispose();
}
}
}
主程序入口
package com.example.i18n;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FormApp app = new FormApp();
app.setVisible(true);
});
}
}
控制台示例(可选)
package com.example.i18n;
import java.util.Locale;
import java.util.Scanner;
/**
* 控制台国际化演示
*/
public class ConsoleDemo {
public static void main(String[] args) {
I18nManager i18n = I18nManager.getInstance();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n=== Language Selection ===");
System.out.println("1. English");
System.out.println("2. 中文");
System.out.println("3. 日本語");
System.out.println("4. Français");
System.out.println("0. Exit");
System.out.print("Choose: ");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline
switch (choice) {
case 1:
i18n.setLocale(Locale.ENGLISH);
break;
case 2:
i18n.setLocale(Locale.SIMPLIFIED_CHINESE);
break;
case 3:
i18n.setLocale(Locale.JAPANESE);
break;
case 4:
i18n.setLocale(Locale.FRENCH);
break;
case 0:
return;
default:
continue;
}
// 演示各种消息
System.out.println(i18n.getMessage("app.welcome"));
System.out.println(i18n.getMessage("app.greeting", "World"));
System.out.println(i18n.getMessage("app.date", "2024-01-15"));
System.out.println(i18n.getMessage("app.money", "€100.50"));
}
}
}
Maven配置(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>i18n-demo</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 无特殊依赖,使用JDK内置功能 -->
</dependencies>
</project>
运行说明
-
编译运行:
mvn clean compile mvn exec:java -Dexec.mainClass="com.example.i18n.Main"
-
或直接使用IDE:导入项目后运行
Main类
关键特性
- 自动语言检测:启动时检测系统默认语言
- 动态切换:运行时切换语言,无需重启
- 参数化消息:支持带占位符的消息
- 数字/日期格式化:根据区域设置正确格式化
- 异常处理:资源加载失败时回退到默认语言
- 线程安全:单例模式保证线程安全
这个案例展示了Java国际化的完整实现,包括资源文件管理、多语言切换、参数化消息等功能,您可以根据需要扩展更多功能。