简体   繁体   English

没有 FXML 的 JavaFX 国际化

[英]JavaFX Internationalization without FXML

I wrote this application to test internationalization:我编写了这个应用程序来测试国际化:

Main.java:主.java:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader();
        loader.setResources(ResourceBundle.getBundle("content", Locale.ENGLISH));
        Parent root = loader.load(getClass().getResource("sample.fxml").openStream());
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

sample.fxml:示例.fxml:

<AnchorPane prefHeight="400.0" prefWidth="600.0" >
   <children>
      <Label layoutX="10.0" layoutY="10.0" text="%label" />
   </children>
</AnchorPane>

content_en.properties: content_en.properties:

label=Hello World

But I can not use FXML for my application.但是我不能在我的应用程序中使用 FXML。 How can I do this without FXML?没有 FXML 我怎么能做到这一点?

If I just add a label and set its text to %label it does not work.如果我只是添加一个标签并将其文本设置为%label它不起作用。

FXMLLoader takes care of texts start with % . FXMLLoader处理以%开头的文本。 If you're not going to use FXML , you can get internationalized texts like this:如果您不打算使用FXML ,您可以获得如下国际化文本:

ResourceBundle rb = ResourceBundle.getBundle("content");
Label label = new Label(rb.getString("label"));

If you want to use the same ResourceBundle everywhere, you can create a class with static methods to return internationalized text values:如果你想在任何地方使用相同的ResourceBundle ,你可以创建一个带有静态方法的类来返回国际化的文本值:

public class I18N {
    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("content");

    public static String getString(String key) {
        return RESOURCE_BUNDLE.getString(key);
    }
}

Then you can use it like this:然后你可以像这样使用它:

Label label = new Label(I18N.getString("label"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM