2
votes

Hi all,

I have knowledge on Java Swings and Applets,but I just started with JavaFX and FXML as I was coding a sample example I was stuck here.

Here I want to show the menu name "File" in some other language(say German) so I had to get the value(German) for it from a variable inside the controller file(java code).

MenuCtrl.java
   public class MenuCtrl extends BorderPane{
      public static String fileMenuName = "Datei";
  }


   Menu.fxml
   <Menu mnemonicParsing="false" text="File">
            <items>
                  <MenuItem mnemonicParsing="false" text="Open" />
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
    </Menu>

How do I make use of fileMenuName variable in 1st line above

<Menu mnemonicParsing="false" text="File">

so that I get

<Menu mnemonicParsing="false" text="Datei">

When I googled I am only getting how build UI Components in FXML using JavaFX Scene Builder Tool but not how to say FXML to use the java file's variables

Please help me thanks In advance

1

1 Answers

4
votes

You're doing it wrong. I'll assume that your code is in package com.abc.def. Now for translations in package com.abc.bundles create file MyStrings.properties:

fileMenuName=File

And in the same place create MyStrings_de.properties:

fileMenuName=Datei

Change your fxml:

<Menu mnemonicParsing="false" text="%fileMenuName">

Notice the % which will instruct fxml loader that this is variable which needs to be found in resources.

Now in java add something like this (I assume that your fxml file is in com.abc.view):

Locale locale = Locale.getDefault(); // or: Locale locale = new Locale("de");
ResourceBundle bundle = ResourceBundle.getBundle("com.abc.bundles.MyStrings", locale);
FXMLLoader loader = new FXMLLoader();
loader.setResources(bundle);
loader.setLocation(MyMain.class.getResource("/com/abc/view/Menu.fxml"));
/* do something with result */ loader.load();

In that way you won't have to hardcode translations in code and it will be easier to translate the app in the future. MyStrings.properties is default file that will be used if no better match is found. So e.g. if you won't have MyStrings_pl.properties and pl language will be used then it will fallback to defaults. But since you have MyStrings_de.properties and de language will be used then it will use that.

If you will need to use translations from code, just use this:

String name = bundle.getString("fileMenuName");