Refresh screen to change JavaFX language

I am creating a JavaFX application with support for multiple languages. Therefore, when loading the fxml file:

 AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("fxml/RealTimeInitialPanel.fxml"),Language.getBundle()); 

I am transferring a resource package based on the default Language . The above Language class extends the ResourceBundle and returns a String based on the current Locale. To change the language, I just need to call Language.setLocale(..) . Everything works well.

But tell me, now the user is changing the language on the go. How to tell fxml or UI to refresh the screen. That way they will call getString(..) again and the text will be updated based on setLocale. In the swing, it is periodically updated. But with fx iam impossible

+4
source share
2 answers

In per FXML Benefits , Question No. 3:

The contents of an FXML file can be localized as you read the file. For example, if an FXML file is loaded using the en_US locale, then it creates a "Name" string for the label based on the following resource string: if the locale is changed to fr_FR and the FXML file is reloaded , then "Prénom" is displayed on the label ....

So, if you are trying to localize an application through FXMLLoader , then you cannot signal FXML to update its embedded texts, except to reload it, I think.

+2
source

Firstly, in the appropriate handler (for example, onAction to select the ComboBox language) you need to update the Locale, for example:

 Locale.setDefault(new Locale(language, country)); 

where you set the values ​​for language and country accordingly.

Then in the corresponding view controller you need to update, install your package:

 bundle = ResourceBundle.getBundle("resources.bundles.SDBundle", Locale.getDefault()); 

(replace the String parameter in the above command with the path to your batch file).

Finally, (still in your view controller that needs to be updated), you start updating each gui element, for example.

 myLabel.setText(bundle.getString("myLabel")); 

This, of course, requires some template for working with package files, etc. and corresponding mapping between keys and values. Check out this great example.

I used the above approach in combination with a properties file, where the language and country values ​​are stored every time they change, so that the application remembers the last choice every time it starts.

0
source

All Articles