【发布时间】:2014-06-06 11:29:26
【问题描述】:
我正在编写一个自定义 JComponent,对于不同的外观和感觉应该看起来不同。我打算至少为WindowsLookAndFeel、MetalLookAndFeel 和MotifLookAndFeel 设置不同的ComponentUi 类。
现在,虽然这项任务看起来很简单,但我不知道如何使用我的自定义 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) - 但这不是我想做的。
【问题讨论】:
标签: java swing custom-component look-and-feel uimanager