如何在FXML文档中实现JavaFX的语言支持? [英] How to implement language support for JavaFX in FXML documents?

查看:156
本文介绍了如何在FXML文档中实现JavaFX的语言支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在FXML文档中为视图提供不同语言以支持多个国家/地区?

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

推荐答案

使用 ResourceBundle s 存储依赖于语言环境的文本,并使用%resourceKey访问包中的数据。

Use ResourceBundles to store the locale-dependent text, and access the data in the bundle using "%resourceKey".

具体来说,为要支持的每种语言创建文本文件,并将它们放在类路径中。 Javadocs for ResourceBundle 有关于命名方案的详细信息,但您应该有一个由 BaseName.properties 定义的默认包以及由其定义的其他语言和变体的包。 BaseName_xx.properties 。例如(使用类路径根目录中的 resources 目录):

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:

resources/UIResources.properties:

greeting = Hello

resources / UIResources_fr.properties:

resources/UIResources_fr.properties:

greeting = Bonjour

然后在你的FXML文件中你可以做到

Then in your FXML file you can do

<Label text = "%greeting" />

ResourceBundle 传递给 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"));

最后,如果您需要访问FXML控制器中的资源包,可以将其注入字段 ResourceBundle 和名称资源

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 ;

    // ...
}

这篇关于如何在FXML文档中实现JavaFX的语言支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆