Reputation: 45
noob here.
I'm trying to implement internationalisation to my command line based program. Below is what is available in the java internationalisation trail.
import java.util.*;
public class I18NSample {
static public void main(String[] args) {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("US");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
System.out.println(messages.getString("greetings"));
System.out.println(messages.getString("inquiry"));
System.out.println(messages.getString("farewell"));
}
}
This obviously works, but I have several classes (currently not in a package). Do I need to load the same bundle in all of these classes in order to use them?
What I'd like to end up with, is at the beginning of the program, let the user choose which language they'd like to use (from a list of available .properties files), by having them enter a command that will load the specific file.
Is this possible?
Thanks
Upvotes: 0
Views: 840
Reputation: 1849
There doesn't seem to be any reason why all of your classes couldn't share the same Locale
and ResourceBundle
. I'm assuming that even though your classes aren't all in the same package, you're using them all within the same application. You just need to make them public or provide public getters. For instance:
public class YourClass {
private static Locale currentLocale;
private static ResourceBundle messages;
static public void main(String[] args) {
String language;
String country;
if (args.length != 2) {
language = new String("en");
country = new String("US");
} else {
language = new String(args[0]);
country = new String(args[1]);
}
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
}
public static Locale getCurrentLocale() {
return currentLocale;
}
public static ResourceBundle getMessages() {
return messages;
}
}
From your other classes, you can call:
Locale currentLocale = YourClass.getCurrentLocale();
ResourceBundle messages = YourClass.getMessages();
Upvotes: 1
Reputation: 7725
You can create a helper class with a public static method for your getString
method. Something like:
public class Messages {
private static Locale locale;
public static void setLocale(Locale locale) {
Messages.locale = locale;
}
public static String getString(String key) {
return ResourceBundle.getBundle("MessagesBundle", locale).getString(key);
}
}
After setting the locale for Messages, you can get messages by
Messages.getString("greetings");
Upvotes: 1