Internationalisation tips for Java and JavaFX

flags

java logo

Java internationalisation (i18n) tips:

I do not like large Resource Bundle files when I write multi-language desktop applications in Swing or JavaFX. So I wanted to use a resource file for each module in my applications. I’ve written a util class  with enum as below. Now I can use this utility from anywhere.

package com.devsniper.lagoserp.util;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Resource Bundle helper.
 * Each module has its own resource bundle file for i18n strings.
 * Always read default locale from Locale.getDefault().
 *
 *
 * Use of I18n:
 * 
 *      I18n.MODULE_NAME.getString("stringKey");
 * 
 *
 * @see ResourceBundle
 *
 * @author cem ikta
 */
public enum I18n {
    // module with resource files
    COMMON("com.devsniper.demoapp.resources.i18n.common"),
    CUSTOMER("com.devsniper.demoapp.resources.i18n.customer"),
    INVOICE("com.devsniper.demoapp.resources.i18n.invoice");

    private ResourceBundle resourceBundle;

    I18n(String bundleFile) {
        resourceBundle = ResourceBundle.getBundle(bundleFile);
    }

    /**
     * Gets a string for the given key from resource bundle.
     *
     * @param key the key for the desired string
     * @return the string for the given key
     */
    public String getString(String key) {
        try {
            return resourceBundle.getString(key);
        } catch (MissingResourceException e) {
            System.err.println(e);

            return "err#";
        }
    }
}

Call to use only I18n.MODULE.getString(“stringKey”)
I have two ResourceBundles common.properties for English and common_de_DE.properties for German.

// set default locale english
Locale.setDefault(new Locale("en", "EN"));
// set default locale for German
// Locale.setDefault(new Locale("de", "DE"));
AppView appView = new AppView();
appView.setTitle(I18n.COMMON.getString("app.title"));