5.5. Call a resource bundle from an application - Source Code

Code:


package c5.s5;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author Mikalai Zaikin
 */
public class MyResources extends ResourceBundle {

    @Override
    public Object handleGetObject(String key) {
        if (key.equals("okButtonLabel")) {
            return "Default.Ok";
        }

        if (key.equals("cancelButtonLabel")) {
            return "Default.Cancel";
        }

        return null;
    }

    @Override
    public Enumeration<String> getKeys() {
        List<String> keys = new ArrayList<>();
        keys.add("okButtonLabel");
        keys.add("cancelButtonLabel");
        return Collections.enumeration(keys);
    }
}

					

Code:

package c5.s5;

/**
 * @author Mikalai Zaikin
 */
public class MyResources_be_BY extends MyResources {

    @Override
    public Object handleGetObject(String key) {
        if (key.equals("okButtonLabel")) {
            return "Добра";
        }

        if (key.equals("cancelButtonLabel")) {
            return "Скасаваць";
        }

        return null;
    }
}
					

Code:

package c5.s5;

/**
 * @author Mikalai Zaikin
 */
public class MyResources_en_US extends MyResources {

    @Override
    public Object handleGetObject(String key) {
        if (key.equals("okButtonLabel")) {
            return "Ok";
        }

        if (key.equals("cancelButtonLabel")) {
            return "Cancel";
        }

        return null;
    }
}
					

Code:

package c5.s5;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author Mikalai Zaikin
 */
public class ResourceBundleDemo {
    public static void main(String... args) {

      ResourceBundle usLabels = ResourceBundle.getBundle("c5.s5.MyResources", new Locale("en", "US"));
      System.out.println("'Ok' button: " + usLabels.getString("okButtonLabel"));
      System.out.println("'Cancel' button: " + usLabels.getString("cancelButtonLabel"));
      System.out.println();

      Locale.setDefault(Locale.GERMANY);
      ResourceBundle defaultLabels = ResourceBundle.getBundle("c5.s5.MyResources");
      System.out.println("'Ok' button: " + defaultLabels.getString("okButtonLabel"));
      System.out.println("'Cancel' button: " + defaultLabels.getString("cancelButtonLabel"));
   }
}
					

output:

'Ok' button: Ok
'Cancel' button: Cancel

'Ok' button: Default.Ok
'Cancel' button: Default.Cancel
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide