我正在编写自定义JComponent
,对于不同的外观和感觉应该看起来不同。我打算至少有WindowsLookAndFeel
,MetalLookAndFeel
和MotifLookAndFeel
不同ComponentUi
类。使用自定义JComponents扩展现有Swing外观和感觉
现在,虽然此任务看起来很简单,但我无法找到如何使用我的自定义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)
- 但这不是我想要做的。
非常感谢你 - 我注册使用'LookAndFeelAddons.contribute自定义组件() '来自SwingX,它就像一个魅力。 – Balder