Internationalization through ResourceBundle and Locale



  • There's a simple class with an interface:

    public class JavaFXApplication25 extends Application {
        String txt = "Say Hello";
        String txt2 = "Hello World!";
        @Override
        public void start(Stage primaryStage) {
            Button btn = new Button(txt);
            Label lbl = new Label();
            Button changeLang = new Button("Изменить язык");
    
        btn.setOnAction(ev -> {
            lbl.setText(txt2);
        });
    
        VBox root = new VBox();
        root.getChildren().addAll(btn,lbl,changeLang);
    
        Scene scene = new Scene(root, 300, 250);
    
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    

    }

    You have to make it through ResourceBundle and Locale so that when you press the "Listen Language" button, the "Hello World" line is replaced by "Hello World!" and the "Say Hello" line on "Say hello" on condition that the relevant files are already in place.properties with the right lines. In other words, we need to change the language of the interface. Help me get this straight.



  • Like that.

    public class Solution extends Application {
    

    @Override
    public void start(Stage primaryStage) {
    initialize(primaryStage, getResourceBundle(Locale.ENGLISH));
    }

    private void initialize(Stage stage, ResourceBundle resourceBundle) {
    Label lbl = new Label();
    Button changeLang = new Button(resourceBundle.getString("button"));

    Button btn = new Button(resourceBundle.getString("change-language-button"));
    btn.setOnAction(ev -> {
        stage.close();
        initialize(stage, getResourceBundle(new Locale("ru")));
    });
    
    VBox root = new VBox();
    root.getChildren().addAll(btn, lbl, changeLang);
    
    Scene scene = new Scene(root, 300, 250);
    
    stage.setTitle(resourceBundle.getString("title"));
    stage.setScene(scene);
    stage.show();
    

    }

    private ResourceBundle getResourceBundle(Locale locale) {
    return ResourceBundle.getBundle("LangBundle", locale);
    }

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




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2