How to implement language support for JavaFX in FXML documents?

こ雲淡風輕ζ 提交于 2019-12-18 15:50:35

问题


How can I have different languages for a view in a FXML document to support many countries?


回答1:


Use ResourceBundles 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 ;

    // ...
}


来源:https://stackoverflow.com/questions/26325403/how-to-implement-language-support-for-javafx-in-fxml-documents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!