Search code examples
javajavafxencodingmultilingual

JavaFX multilanguage .properties file encoding


I have a problem with displaying characters with diacritic like á, í, č, etc. I've set .properties file to UTF-8 with ISO 8599-1 but when I run following code I dont have wanted result.

Main class:

@Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setResources(ResourceBundle.getBundle("bundles.language_sk", new Locale("sk", "SK")));
            Parent root = fxmlLoader.load(getClass().getResource("/view/loginFrame.fxml"));
            primaryStage.setTitle("Login");
            Scene scene = new Scene(root, 563, 580);
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        }

Login Frame controller class:

@Override
    public void initialize(URL location, ResourceBundle resources) {
        ResourceBundle bundle = ResourceBundle
                .getBundle("bundles.language_sk", new Locale("sk", "SK"));
        setLoginBtnText(bundle);
    }

    public void setLoginBtnText(ResourceBundle bundle){
            loginBtn.setText(bundle.getString("loginButton"));
    }

language_sk.properties file:

#LOGIN FRAME
.
.
loginButton=Prihlásiť
.
.

Result:

enter image description here

So as you can see, I've tried to set text of Login Button using .properties file but characters are messed up.

Although when I use this code in setLoginBtnText method:

 public void setLoginBtnText(ResourceBundle bundle){
        String val = bundle.getString("loginButton");
        try {
            loginBtn.setText(new String(val.getBytes("ISO-8859-1"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

then text on button is perfectly fine. How can I set some global encoding settings for my whole project so I dont have to specify encoding at each one component in each class? Thanks.


Solution

  • Few things:

    • "set .properties file to UTF-8 with ISO 8599-1" doesn't mean anything. It is UTF-8 OR ISO 8859-1, not both
    • it seems that your property file is in UTF-8 encoding on the disk (you can check it with hex editor - you will see two bytes for each special character)
    • locale you are passing to ResourceBundle initializer is not helping with language/charset decoding, it is just used to select proper bundle; if you are passing _sk in name yourself, then it is probably not needed
    • ResourceBundle understands only ISO 8859-1 by default from what I understand and I don't think that all SK characters are there

    What you need is UTF-8 encoded resource bundle (which you seem to have by accident) and load it as such. Please look here for description how to do it How to use UTF-8 in resource properties with ResourceBundle