Dynamically Switch Locales in GWT

Like me, a lot of people want their GWT applications to be able to change locale on the fly. While mine still only has one locale, I wanted to make sure that it could expand to more if necessary. Here's how I implemented dynamic local switching.

First, I store my languages in an XML configuration file, along with some other stuff for the application. A language element looks like this:

<language default="true">
	<key>myapp.language.name.english</key>
	<abbreviation>en</abbreviation>
	<icon>us.gif</icon>
	<email>translation@email.com</email>
</language>

This allows me to dynamically display the available languages to users of my app using clickable graphics. I use country flags.

Then I store my localized strings in a Java XML properties file. Like this:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
	<comment>This is the English translation for MyApp</comment>
	<entry key="myapp.language.name.english">English</entry>
</properties>

On load of my application, I read the configuration file and get the default language (or use the user's last language choice from a cookie value or the browser's locale, see Get Locale via Javascript for more info). Then, on demand, I get the messages_.xml file, like above, for that language, using an increasingly general locale. If none is found, then it'll use messages.xml, which is the English language for my app.

Now, to make this dynamically change, you have implement a listener to all of the classes in your application that display localized text for when the user changes the language. Then you have to add those listeners, usually the class itself, to the class that handles the changes in language.