Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

java - How to implement language support for JavaFX in FXML documents?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ;

    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...