Share this page 

Localize a JOptionPane dialogTag(s): Internationalization Swing


This example will show 2 radio buttons, one for english messages and buttons and the other one for french. Press the button to display a localized JOptionPane according to the radio button selected.

Create 2 properties files, one for english , one for french.

[JOptionPane_en.properties]
Yes=Yes
No=No
Cancel=Cancel
SaveMsg=Do you want to save your data
[JOptionPane_fr.properties]
Yes=Oui
No=Non
Cancel=Annuler
SaveMsg=Voulez-vous sauvegarder vos donnees

Then

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class MessageBoxExample extends JPanel
   implements ActionListener {
   JButton go;
   AbstractButton button;
   ButtonGroup group;
   Locale locale;
   String msg ;
   
  public MessageBoxExample() {
    group = new ButtonGroup();

    locale = Locale.US;  // default value
    button = new JRadioButton("English", true);
    button.setActionCommand("en");
    button.addActionListener(this);
    group.add(button);
    add(button);

    button = new JRadioButton("Francais");
    button.setActionCommand("fr");
    button.addActionListener(this);
    group.add(button);
    add(button);

    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
    
    locale = Locale.US;
    }

 public void setUILanguage() {
   ResourceBundle rb;
   rb = ResourceBundle.getBundle("JOptionPane", locale);
   
   UIManager.put("OptionPane.yesButtonText", rb.getString("Yes"));
   UIManager.put("OptionPane.noButtonText", rb.getString("No"));
   UIManager.put("OptionPane.cancelButtonText", rb.getString("Cancel"));
   msg = rb.getString("SaveMsg");
   }

  public void actionPerformed(ActionEvent e) {
    int result;
        
    if (e.getSource() instanceof JRadioButton) {
      if (e.getActionCommand().equals("en"))
         locale = Locale.US;
      else
         locale = Locale.FRANCE; 
      setUILanguage();
      }
    else {
      // the button action
      result = JOptionPane.showConfirmDialog(this,msg);
      System.out.println(result);
      }
     }
   
  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }
    
  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    MessageBoxExample panel = new MessageBoxExample();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}