4

I am building a JavaFX application with multi language support. So while loading the fxml file by:

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

I am passing the resource bundle based on the default Language. Above Language class extends ResourceBundle and returns String based on the current Locale. To change language, I just have to call up Language.setLocale(..). Everything works well.

But say now the user changes the language on the go. How do I signal the fxml or UI to refresh the screen. That way they will again call up getString(..) and the text gets updated based on the setLocale. In swing, it does refresh periodically. But with fx iam unable to

Jatin
  • 31,116
  • 15
  • 98
  • 163

2 Answers2

2

At per Benefits of FXML, matter no 3:

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

So if you are aiming to localize the app through FXMLLoader then you cannot signal FXML to refresh its bundled texts other than reloading it again, I think.

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
  • Thanks, that is what I am currently doing. But I am afraid as the UI gets bigger, reloading would take longer time. And also I will have to reinitialize the UI with modal – Jatin Feb 01 '13 at 04:31
0

First, in the respective handler (e.g. the onAction of the e.g. ComboBox language chooser) you need to update the Locale, e.g:

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

where you have appropriately set the values for language and country.

Then in the respective controller of the view you need to update, set your bundle:

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

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

Finally, (still in your controller of the view you need to update) you start updating each gui item, e.g.

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

This needs of course some boilerplate work with bundle files etc and the appropriate mapping between keys and values. Check this excellent example.

I have used the aforementioned approach in combination with a properties file where language and country values are stored each time they change so that the app remembers last selection each time it starts.

Community
  • 1
  • 1
pkaramol
  • 16,451
  • 43
  • 149
  • 324