3

I need my application to set programmatically a locale of all the sensitive components, like JTextFields and JTextAreas. Also I have date information (month written as a word) which is locale-sensitive too.

I wrote the following code, but it doesn't seem to do the job:

    public static void setLocale(java.awt.Container c /* main form */, Locale locale /* Locale.ENGLISH */) {

        Component[] components = c.getComponents();

        for (Component comp : components) {
            if (comp instanceof java.awt.Container)
                setLocale((java.awt.Container) comp, locale);
            comp.setLocale(locale);    
        }
    }

What's wrong with the code?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
ilja
  • 95
  • 8
  • What is the failure you're seeing? Do you get errors? Does it work on some of the components and not the others? Does it fail entirely? Are you sure you're passing a valid Locale? – g051051 Aug 04 '11 at 14:16

2 Answers2

0

Basically, I don't see a reason to change the locale of all components in the component tree. Since the method getLocale() automatically searches its parents.

/**
 * Gets the locale of this component.
 * @return this component's locale; if this component does not
 *          have a locale, the locale of its parent is returned
 */
public Locale getLocale();

So it should be enough to set the locale of the root of the tree. But whether the locale is respected somewhere, I can't tell right now.

Bye

0

The following code should do the trick:

public void switchDefaultLocale(Locale l) {
    if (! l.equals(Locale.getDefault())) {
        Locale.setDefault(l);
        JComponent.setDefaultLocale(l);
    }
}

But this will have an effect only on new instance of JComponent. If you want to update existing instances, don't forget to call updateUI() on each.

Adrien Clerc
  • 2,636
  • 1
  • 21
  • 26
  • 1
    this one doesn't work for some reason... i did JComponent.setDefaultLocale(Locale.ENGLISH); and ive ran updateUI on 4 of my textfields and 1 textarea... no effect – ilja Aug 07 '11 at 10:58