JavaFX Internationalization without FXML

Noah :

I wrote this application to test internationalization:

Main.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:

<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

But I can not use FXML for my application. How can I do this without FXML?

If I just add a label and set its text to %label it does not work.

M. S. :

FXMLLoader takes care of texts start with %. If you're not going to use FXML, you can get internationalized texts like this:

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:

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"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3580&siteId=1