这是我的
StartApp.java
,我的应用程序的入口点。
public class StartApp extends Application {
private Locale locale = new Locale("en");
public Locale getLocale(){
return locale;
}
public void setLocale(Locale locale){
this.locale = locale;
}
@Override
public void start(Stage primaryStage) throws Exception{
ResourceBundle bundle = ResourceBundle.getBundle("resources.bundles/MyBundle", locale);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/LoginView.fxml"), bundle);
Parent root = fxmlLoader.load();
primaryStage.setTitle("Title");
primaryStage.setScene(new Scene(root, 750, 400));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) throws SQLException {
launch(args);
}
然后在
LoginController.java
我创建 StartApp 实例并为 2 个按钮设置 onActions
StartApp startApp = new StartApp();
@Override
public void initialize(URL location, ResourceBundle resources) {
bundle = resources;
plBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
startApp.setLocale(new Locale("pl"));
changeLanguage(event);
} catch (Exception e) {
e.printStackTrace();
}
}
});
enBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
startApp.setLocale(new Locale("en"));
changeLanguage(event);
} catch (Exception e) {
e.printStackTrace();
}
}
});
这是我的
changeLanguage
方法,它刷新当前窗口并更改其语言
public void changeLanguage(ActionEvent event) throws Exception{
((Node)event.getSource()).getScene().getWindow().hide();
Stage primaryStage = new Stage();
ResourceBundle bundle = ResourceBundle.getBundle("resources.bundles/MyBundle", startApp.getLocale());
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/LoginView.fxml"), bundle);
Parent root = fxmlLoader.load();
primaryStage.setTitle("Title2");
primaryStage.setScene(new Scene(root, 750, 400));
primaryStage.setResizable(false);
primaryStage.show();
}
到目前为止,一切正常,一旦我单击按钮,它就会改变语言。但我现在想做的是用选择的语言打开新窗口(舞台),但不幸的是,它总是用 StartApp 上设置的语言打开新场景。
这是
LoginController
中打开新阶段的方法。
public void register(ActionEvent event) throws Exception{
((Node)event.getSource()).getScene().getWindow().hide();
Stage primaryStage = new Stage();
ResourceBundle bundle = ResourceBundle.getBundle("resources.bundles/MyBundle", startApp.getLocale());
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/RegisterView.fxml"), bundle);
Parent root = fxmlLoader.load();
primaryStage.setTitle("Title2");
primaryStage.setScene(new Scene(root, 750, 400));
primaryStage.setResizable(false);
primaryStage.show();
}
顺便说一句。 Iv 尝试将 StartApp 扩展到 LoginController,将语言环境公开等等,每次结果都是一样的。当我创建时
Locale newLocale = null;
在
LoginController
中,然后在单击 initialize
中定义的按钮后尝试为其赋值,出现 nullpointerexception。
我不知道如何通过一个命令更改所有文本。 为了保持简单,我只是分别重命名每个元素。
示例:
i18n/messages.properties
label.welcome = Welcome
i18n/messages_ukr.properties
label.welcome = Ласкаво просимо
Singleton Context.java 将包含当前语言环境:
public class Context {
private final List<Locale> availableLocales;
private Locale currentLocale;
private static Context instance;
public static Context getInstance() {
if (instance == null) {
instance = new Context();
}
return instance;
}
private Context() {
availableLocales = new LinkedList<>();
availableLocales.add(new Locale("eng"));
availableLocales.add(new Locale("ukr"));
currentLocale = new Locale("eng"); // default locale
}
/**
* This method is used to return available locales
*
* @return available locales
*/
public List<Locale> getAvailableLocales() {
return availableLocales;
}
/**
* This method is used to return current locale setting
*
* @return current locale
*/
public Locale getCurrentLocale() {
return currentLocale;
}
/**
* This method is used to set current locale setting
*
* @param currentLocale locale to set
*/
public void setCurrentLocale(Locale currentLocale) {
this.currentLocale = currentLocale;
}
Util 类 MessageUtil.java 将返回当前语言环境中的消息(在上下文中设置):
/**
* This class is used to provide methods to work with localized messages
*
* @author manfredi
*/
public abstract class MessageUtil {
private final static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
private final static String RESOURCE_NAME = "i18n.messages";
/**
* This method is used to return resource bundle with current locale
*
* @return resource bundle with current locale. Otherwise resource bundle with default locale.
*/
public static ResourceBundle getResourceBundle() {
return ResourceBundle.getBundle(RESOURCE_NAME, Context.getInstance().getCurrentLocale());
}
/**
* This method is used to return localized message by it`s {@code key}
*
* @param key message key
* @return localized message
*/
public static String getMessage(String key) {
String message;
try {
message = getResourceBundle().getString(key);
} catch (MissingResourceException e) {
logger.error("{}", e.getMessage());
message = key;
}
return message;
}
/**
* This method is used to format localized message by it`s {@code key} using {@code args} as arguments list
*
* @param key message key by which the corresponding message will be found
* @param args list of arguments used in the message
* @return formatted localized message
*/
public static String formatMessage(String key, Object... args) {
MessageFormat messageFormat = new MessageFormat(getMessage(key), getResourceBundle().getLocale());
return messageFormat.format(args);
}
}
我使用 SceneBuilder 工具创建 *.fxml 文件。 例如,包含用于语言更改的 Label 和 ChoiceBox 的此文件之一的屏幕控制器可能如下所示:
public class LanguageChangeScreenController implements Initializable {
@FXML
private Label welcomeLabel;
@FXML
private ChoiceBox<Locale> languageChoiceBox;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
initLanguageChangeListener();
refreshLocalization(); // I use %key.name syntax in .fxml files to initialize component's names instead of calling this method here
}
**
* This method is used to update the name of each component on the screen
*/
private void refreshLocalization() {
welcomeLabel.setText(MessageUtil.getMessage("label.welcome"));
}
private void initLanguageChangeListener() {
languageChoiceBox.getItems().addAll(Context.getInstance().getAvailableLocales());
languageChoiceBox.getSelectionModel().select(Context.getInstance().getCurrentLocale());
languageChoiceBox.setOnAction(actionEvent -> {
Context.getInstance().setCurrentLocale(languageChoiceBox.getSelectionModel().getSelectedItem());
refreshLocalization();
});
}
}