我正在写一个 custom JComponent
,对于不同的外观和感觉应该看起来不同。我打算ComponentUi
至少为WindowsLookAndFeel
、MetalLookAndFeel
和MotifLookAndFeel
.
ComponentUi
现在,虽然这个任务看起来很简单,但我不知道如何使用我的自定义类轻松扩展现有的外观和感觉。
我将如何ComponentUi
为不同的外观和感觉注册正确的?这可能吗?如果不是,为不同的外观和感觉编写自定义组件的首选方法是什么?
更具体地说,目前我JComponent#updateUI
在我的自定义组件中重写以设置不同的ComponentUi
实例:
@Override
public void updateUI() {
LookAndFeel feel = UIManager.getLookAndFeel();
if (feel instanceof WindowsLookAndFeel) {
setUI(MyWindowsCustomUi.createUI(this));
} else if (feel instanceof MotifLookAndFeel) {
setUI(MyMotivCustomUi.createUI(this));
} else if (feel instanceof MetalLookAndFeel) {
setUI(MyMetalCustomUi.createUI(this));
} else{
setUI(MyBasicCustomUi.createUI(this));
}
}
但这种方法似乎完全违背了外观的目的和用途。我希望能够将其更改为以下内容:
public void updateUI() {
setUI((MyCustomUi)UIManager.getUI(this));
}
这应该MyCustomUi
为当前的外观设置正确的子类。
我知道,我可以通过创建每个受支持的自定义子类来轻松实现这一点,这些子类在例如期间LookAndFeel
注册相应的- 但这不是我想要做的。ComponentUi
BasicLookAndFeel#initComponentDefaults(UIDefaults)