【问题标题】:JavaFX changing Locale in whole applicationJavaFX 在整个应用程序中更改语言环境
【发布时间】:2017-05-09 07:09:22
【问题描述】:

这是我的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 中定义的按钮后尝试为其分配值,但出现空指针异常。

【问题讨论】:

  • 当你重新加载LoginView.fxml时,它会创建一个新的控制器;在该控制器中,您创建StartApp 的新实例,并且您没有在该实例上设置语言环境。这里的方法似乎是错误的:创建您自己的Application 子类实例基本上总是一个坏主意:应该只有一个实例(为您创建的实例,在其上调用start(...))。尝试为此使用 MVC 方法,并将语言环境(或者可能是资源包)作为属性包含在模型中。然后只需与所有控制器共享一个模型实例。

标签: javafx locale resourcebundle


【解决方案1】:

我不知道如何通过一个命令更改所有文本。 为了保持简单,我只是分别重命名每个元素。

例子:

i18n/messages.properties

label.welcome = Welcome

i18n/messages_ukr.properties

label.welcome = Ласкаво просимо

i18n/messages_rus.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"));
        availableLocales.add(new Locale("rus"));
        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();
        });
    }
}

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2011-03-24
    • 2015-12-04
    • 1970-01-01
    • 2014-05-26
    • 2011-09-04
    • 2013-04-01
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多