Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing locale at runtime in Swing

I would like to be able to change the locale in my Swing application at runtime and have all the text elements on the screen update themselves with localized text from a ResourceBundle of the new locale.

Can this be done without customizing swing components or creating UIDelegates for all components that handle rendering localized text?

If no, then what is a good solution I can consider implementing?

like image 545
Tony Eichelberger Avatar asked Mar 05 '09 18:03

Tony Eichelberger


3 Answers

use ResourceBundle.getBundle(BUNDLE_NAME).getString(key); to access the Strings.

when updating the Default Locale e.g. via Locale.setDefault(Locale.GERMAN); clear the Resourcebundle cache: ResourceBundle.clearCache();

the next call of ResourceBundle.getBundle(BUNDLE_NAME).getString(key); should the return the localized String of the chosen Locale.

like image 199
Marc Avatar answered Nov 03 '22 14:11

Marc


  1. You have a method that is used to change app locale (and probably persist the new value) and another one to get localized strings.

  2. Create an interface:

    interface LocaleChangeListener {
        void onLocaleChange();
    }
    

    Implement it by UI components that need to be able to change locale at runtime and set the new values in overrides onLocaleChange().

  3. Now, have a list of listeners that will be notified on locale change by the first method.

like image 22
yanchenko Avatar answered Nov 03 '22 13:11

yanchenko


You may want to save the language preference out, and then require a restart of the app for changes to take effect.

Then, you should be able to use Locale.setDefault(Locale.<desired language>); on startup, prior to rendering the GUI. That should properly switch your locale, which will result in the desired .properties file(s) being loaded.

like image 42
James Van Huis Avatar answered Nov 03 '22 14:11

James Van Huis