在JavaFX中使用FXML進行國際化,你需要遵循以下步驟:
準備翻譯文件:首先,為你的應用程序創建多個翻譯文件,每個文件對應一種語言。這些文件應該使用Java屬性文件格式,例如messages_en.properties
(英語)和messages_zh.properties
(中文)。在這些文件中,使用鍵值對的形式存儲翻譯后的文本。例如:
messages_en.properties
:
welcome.message=Welcome to our application!
exit.message=Exit the application
messages_zh.properties
:
welcome.message=歡迎使用我們的應用程序!
exit.message=退出應用程序
創建資源束類:為了在FXML文件中引用翻譯文本,你需要創建一個資源束類(ResourceBundle class),該類將加載適當的翻譯文件。例如:
public class Resources {
private static final ResourceBundle messages = ResourceBundle.getBundle("messages", Locale.getDefault());
public static String getString(String key) {
return messages.getString(key);
}
}
在FXML文件中引用翻譯文本:在FXML文件中,使用${key}
的形式引用翻譯文本。例如:
<Label text="${Resources.getString('welcome.message')}" />
<Button text="${Resources.getString('exit.message')}" onAction="#handleExit" />
加載FXML文件:在Java代碼中,使用FXMLLoader
加載FXML文件。為了確保正確加載翻譯文件,你需要在FXMLLoader
的構造函數中指定基礎路徑,該路徑應包含所有翻譯文件的文件夾。例如:
FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/your/fxml/files"));
切換語言:要更改應用程序的語言,只需更改Locale
對象并重新加載FXML文件。例如:
Locale.setDefault(new Locale("zh", "CN"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/your/fxml/files"));
遵循這些步驟,你就可以在JavaFX中使用FXML實現國際化了。