How can I have different languages for a view in a FXML document to support many countries?
1 Answers
Use ResourceBundle
s to store the locale-dependent text, and access the data in the bundle using "%resourceKey"
.
Specifically, create text files for each language you want to support and place them in the classpath. The Javadocs for ResourceBundle
have the details on the naming scheme, but you should have a default bundle defined by BaseName.properties
and bundles for other languages and variants defined by BaseName_xx.properties
. For example (with the resources
directory in the root of the classpath):
resources/UIResources.properties:
greeting = Hello
resources/UIResources_fr.properties:
greeting = Bonjour
Then in your FXML file you can do
<Label text = "%greeting" />
To pass the ResourceBundle
to the 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 load the resource bundle corresponding to the default locale (typically the locale you have set at the OS level), falling back on the default if it can't find a corresponding bundle. If you want to force it to use a particular bundle, you can do
ResourceBundle bundle = ResourceBundle.getBundle("/resources/UIResources", new Locale("fr"));
Finally, if you need access to the resource bundle in the FXML controller, you can inject it into a field of type ResourceBundle
and name resources
:
public class MyController {
@FXML
private ResourceBundle resources ;
// ...
}

- 201,275
- 16
- 291
- 322
-
I can't put ResourceBundle on the ContextMenu. Can you help me – Krismorte Feb 17 '16 at 02:40
-
In fact for those who still wonder, the bundle parameter is to be put in the call of the load method or constructor as a second parameter! – Alexandre Pieroux Oct 28 '16 at 14:16
-
@AlexandrePieroux Doesn't the answer explicitly say that? "To pass the `ResourceBundle` to the `FXMLLoader` do..." – James_D Oct 28 '16 at 14:21
-
In the example it actually pass the bundle to the getResource method. Just showing that there is a typo in the examples -> a parenthesis is missing right before the coma. – Alexandre Pieroux Oct 28 '16 at 22:54
-
1@AlexandrePieroux Ah, I see. Thanks; I fixed it. – James_D Oct 28 '16 at 22:56
-
@James_D what if I need to pass a parameter? if I have in bundle key=translation {1}, how do I use that in the fxml? – Laura Nov 14 '17 at 07:47