How to bind text to jlabel in Java?
There are several GUI forms in my java application All tables have text I set text for my component from a shared object called dictionary I need a function in my program; Switch languages according to user needs; In this way, all text in all forms can be replaced in another language I have all the text in the shared dictionary object Is there a clean way to change language in a clean way?
Edit: for example:
And dictionary classes are defined as:
public class Dictionary { public static String Hello = "hello"; }
Another language:
public class DictionaryPersian extends Dictionary { public DictionaryPersian(){ Hello = "درود"; } }
I want to find a way to put the field dictionary Hello is bound to jlabel1, so that when the variable value changes, it will be reflected in jlabel1 text
Solution
For example, you can subclass jlabel and use some IDs to set text directly from the dictionary It can also act as a listener for text or language changes to automatically change the displayed text accordingly
To explain some code snippets (untested and incomplete, dictionary tags can be implemented in different ways if you like, and your dictionary should also implement idictionary)
public interface IDictionaryListener { void dictionaryChanged(IDictionary from,IDictionary to); } public interface IDictionary { String getString(String forKey); } public final class DictionaryManager { private static final DictionaryManager INSTANCE=new DictionaryManager(); private final List<IDictionaryListener> listeners=new ArrayList<>(); private IDictionary dictionary; private DictionaryManager() {}; public static synchronized void setDictionary(IDictionary dict) { IDictionary old = INSTANCE.dictionary; INSTANCE.dictionary=dict; fireDictionaryChanged(old,dict); } public static synchronized IDictionary getDictionary() { return INSTANCE.dictionary; } public static synchronized void addDictionaryListener(IDictionaryListener l) { INSTANCE.listeners.add(l); } public static synchronized void removeDictionaryListener(IDictionaryListener l) { INSTANCE.listeners.remove(l); } private static void fireDictionaryChanged(IDictionary from,IDictionary to) { for (IDictionaryListener l:INSTANCE.listeners) { l.dictionaryChanged(from,to); } } } public class DictionaryLabel extends JLabel implements IDictionaryListener { private String key; public DictionaryLabel(String dictKey) { super(); key = dictKey; DictionaryManager.addDictionaryListener(this); super.setText(DictionaryManager.getDictionary().getString(key)); } @Override public final void setText(String text) { throw new RuntimeException("Not supported! Dictionary is used for this!"); } @Override public void dictionaryChanged(final IDictionary from,final IDictionary to) { SwingUtilities.invokelater(new Runnable() { @Override public void run() { DictionaryLabel.super.setText(to.getString(key)); } }); } }
As I said, just some examples are cut off. I hope you can get this idea