HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Working with Locales in Swing (with change at runtime)?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withruntimeworkingswinglocaleschange

Problem

I thought about the best way to implement localisation with runtime in Swing.

I currently solve the problem like that:

JMenu menuData = new JMenu("Data");
    menuData.setName("mainframe.menu.data"); // property key
    localeChangedListener.add(menuData);


The LocaleChangedListener:

public class SwingLocaleChangedListener implements LocaleChangedListener {

    private ArrayList   abstractButtons;

    @Override
    public void localeChanged(ResourceBundle rb) {
        logger.info("Locale changed to '" + rb.getLocale() + "'");
        for (AbstractButton b : abstractButtons) {
            b.setText(rb.getString(b.getName()));
            b.setComponentOrientation(ComponentOrientation.getOrientation(rb.getLocale())); //EDIT: Line added
        }

    }

    public boolean add(AbstractButton b) {
        initAbstractButtons();
        return abstractButtons.add(b);
    }

    private void initAbstractButtons() {
        if (abstractButtons == null) {
            this.abstractButtons = new ArrayList();
        }
    }
}


And the registration of the Listener:

```
public class GuiBundleManager {

private String filePrefix = "language.lang";
private ResourceBundle rb = null;
private LocaleChangedListener listener = null;

private static GuiBundleManager instance = null;

private GuiBundleManager() {
setLocale(Locale.getDefault());
}

public String getString(String key) {
return rb.getString(key);
}

public String[] getStringArray(String key) {
return rb.getStringArray(key);
}

public Locale getLocale() {
return rb.getLocale();
}

public void setLocale(Locale l) {
rb = ResourceBundle.getBundle(filePrefix, l);
if (listener != null) {
listener.localeChanged(rb);
}
}

public LocaleChangedListener getLocaleChangedListener() {
return listener;
}

public void setLocal

Solution

Consider applyComponentOrientation(), which recursively "Sets the ComponentOrientation property of this component and all components contained within it." Examples may be found here.

Context

StackExchange Code Review Q#13251, answer score: 3

Revisions (0)

No revisions yet.