2012-03-02 45 views
4

我在我的java應用程序中有幾個GUI窗體。所有表格都有文字。我從一個名爲字典的共享對象中爲我的組件設置了文本。我需要一個功能在我的程序中;根據用戶需要切換語言;使所有形式的所有文本都被替換爲另一種語言。我有一個共享的Dictionary對象中的所有文本。有沒有乾淨的方式來改變語言的乾淨方式? 我知道netbeans國際化工具,但我想用另一種方法。如何在java中將文本綁定到JLabels?

編輯:例如:

label1.setText(Dictionary.Hello);

和字典類定義爲:

public class Dictionary { 
    public static String Hello = "hello"; 
} 

和另一種語言:

public class DictionaryPersian extends Dictionary { 
     public DictionaryPersian(){ 
      Hello = "درود"; 
     } 
    } 

我想找到一種方法的方式到外地Dictionary.hello到jLabel1的這種結合當這個變量值改變時,它會反映在jlabel1文本中。

回答

1

例如,您可以繼承JLabel的子類,直接使用某個id從字典中設置文本。它也可以用作文本或語言更改的監聽器,以相應地自動更改顯示的文本。

爲了闡述的緣故剪掉一些代碼(未測試,也不完整,詞典標籤可以有不同的實現,如果你喜歡,還你的字典應該實現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)); 
     } 

    }); 
    } 
} 

正如我所說的,只是一些例子剪斷我希望你明白這個主意。

+0

如果可能的話,請參閱我的編輯。 – sajad 2012-03-02 20:47:22

+0

如果你願意的話,你需要的是一個DictionaryManager,它有關於cutrent選擇的字典的信息,如果你願意的話可以使用。它還應提供監聽器支持,允許通知註冊標籤,按鈕等詞典變化 – stryba 2012-03-02 20:51:50

+0

有點複雜但好主意。感謝您的關注和幫助! – sajad 2012-03-03 16:39:44