Nikola Luburic
Nikola Luburic

Reputation: 153

Can I localize the JOptionPane Yes/No/Cancel option?

I have a question regarding the JOptionPane.showConfirmDialog. The buttons I get are Yes, No and Cancel, but I was wondering if it was possible to localize these three buttons to my language? I realize I can just create a confirmation dialogue of my own with my JButtons but I was wondering if this was possible as well.

Thanks in advance.

Upvotes: 7

Views: 10894

Answers (3)

BZM
BZM

Reputation: 41

This is enough:

UIManager.put("OptionPane.yesButtonText", "Ya");

etc

Upvotes: 4

Sergey Ushakov
Sergey Ushakov

Reputation: 2473

All the localized messages for standard dialogs for most used languages, German included, are provided by Swing PLAF resource bundles, and you can find them in the JDK sources. See e.g. for messages in English:

String values for languages other than English are provided by adjacent bundle files.

And in case of a rarely used language you can add one more bundle to any of these families just by creating one more file for desired language and placing it anywhere on your classpath. Bundles in .java and .properties format work equally well, though .java format may be slightly more Unicode-friendly...

It may be good to keep in mind though that direct adding of content to com.sun package may violate the Java license. So to be on the safe side, it may be wise to move your extra resources to a package of your own and register it with UIManager like this:

UIManager.getDefaults().addResourceBundle("mypackage.swing.plaf.basic.resources.basic");

Upvotes: 2

jfajunior
jfajunior

Reputation: 1251

The simple way is to set the JOptionPane with the desired locale, like this:

Locale locale = new Locale("pt","BR");
JOptionPane.setDefaultLocale(locale);

If you have a singleton class that treats all the messages from your ResourceBundle, then you just need to set it once in the locale initialization. For example:

public void setLocale(Locale locale) {
    if (_bundle == null || !locale.equals(_locale)) {
        _locale = locale;
        _bundle = ResourceBundle.getBundle("resources.i18n.MessagesBundle", locale);

        JOptionPane.setDefaultLocale(_locale);

        _logger.info("Got new resource bundle for language-country: " + _locale.getLanguage() + "-" +
                locale.getCountry());
    }
}

Cheers!

Upvotes: 13

Related Questions