java 如何在 FXML 文档中实现对 JavaFX 的语言支持?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26325403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement language support for JavaFX in FXML documents?
提问by Marcel H?ll
How can I have different languages for a view in a FXML document to support many countries?
如何为 FXML 文档中的视图使用不同的语言以支持多个国家/地区?
回答by James_D
Use ResourceBundle
sto store the locale-dependent text, and access the data in the bundle using "%resourceKey"
.
使用ResourceBundle
s存储与语言环境相关的文本,并使用 访问包中的数据"%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):
具体来说,为您想要支持的每种语言创建文本文件并将它们放在类路径中。的JavadocsResourceBundle
有关于命名方案的详细信息,但您应该有一个BaseName.properties
由BaseName_xx.properties
. 例如(resources
在类路径的根目录中的目录):
resources/UIResources.properties:
资源/UIResources.properties:
greeting = Hello
resources/UIResources_fr.properties:
资源/UIResources_fr.properties:
greeting = Bonjour
Then in your FXML file you can do
然后在你的 FXML 文件中你可以做
<Label text = "%greeting" />
To pass the ResourceBundle
to the FXMLLoader
do:
将 传递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"));
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
:
最后,如果您需要访问 FXML 控制器中的资源包,您可以将其注入一个 typeResourceBundle
和 name字段resources
:
public class MyController {
@FXML
private ResourceBundle resources ;
// ...
}