How to implement JavaFX language support in FXML documents?

How can I use different languages ​​for viewing in an FXML document to support many countries?

+5
source share
1 answer

Use ResourceBundle s to store language dependent text and access data in the bundle using "%resourceKey" .

In particular, create text files for each language that you want to support and put in the classpath. Javadocs for the ResourceBundle contain naming scheme information, but you should have a default set defined by BaseName.properties and bundles for other languages ​​and options defined by BaseName_xx.properties . For example (with the resources directory in the root of the class path):

resources / UIResources.properties:

 greeting = Hello 

resources / UIResources_fr.properties:

 greeting = Bonjour 

Then in your FXML file you can do

 <Label text = "%greeting" /> 

To pass a ResourceBundle to FXMLLoader do:

 ResourceBundle bundle = ResourceBundle.getBundle("resources.UIResources"); FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/FXML.fxml"), bundle); Parent root = loader.load(); 

This code will download the resource package that matches the standard language (usually the language that you installed at the OS level) when returning by default if it cannot find the corresponding package. If you want to force it to use a specific package, you can do

 ResourceBundle bundle = ResourceBundle.getBundle("/resources/UIResources", new Locale("fr")); 

Finally, if you need access to the resource package in the FXML controller, you can enter it in a field of type ResourceBundle and the name resources :

 public class MyController { @FXML private ResourceBundle resources ; // ... } 
+18
source

Source: https://habr.com/ru/post/1204508/


All Articles