Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Internationalization without FXML

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.

like image 377
Noah Avatar asked Feb 24 '20 14:02

Noah


1 Answers

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"));
like image 198
Miss Chanandler Bong Avatar answered Sep 22 '22 07:09

Miss Chanandler Bong