簡體   English   中英

沒有 FXML 的 JavaFX 國際化

[英]JavaFX Internationalization without FXML

我編寫了這個應用程序來測試國際化:

主.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);
    }
}

示例.fxml:

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

content_en.properties:

label=Hello World

但是我不能在我的應用程序中使用 FXML。 沒有 FXML 我怎么能做到這一點?

如果我只是添加一個標簽並將其文本設置為%label它不起作用。

FXMLLoader處理以%開頭的文本。 如果您不打算使用FXML ,您可以獲得如下國際化文本:

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

如果你想在任何地方使用相同的ResourceBundle ,你可以創建一個帶有靜態方法的類來返回國際化的文本值:

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

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

然后你可以像這樣使用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM