java jlabel如何继承,如何将文本绑定到Java中的JLabel?

例如,您可以将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 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));

}

});

}

}

正如我所说,只是一些例子剪断了我希望你能得到这个想法.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值