How can I have different languages for a view in a FXML document to support many countries?
You don't have to use FXML or SceneBuilder. You can simply create the objects yourself and add them to your Scene/Stage yourself. It's entirely open as to how you implement it. I've implemented a Screen Management library where it handles either FXML or manually created screens.
The JavaFX application package that is generated by default includes: An executable application JAR file, which contains application code and resources and can be launched by double-clicking the file. Additional application JAR and resource files. A deployment descriptor for web deployment (kept in the JNLP file)
JavaFX controller works based on MVC(Model-View-Controller) JavaFX MVC can be achieved by FXML (EFF-ects eXtended Markup Language). FXML is an XML based language used to develop the graphical user interfaces for JavaFX applications as in the HTML.
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 ;
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With