下面是我想出了破解。缺点是:
- ,如果你想保持外观和感觉,你必须单独继承每个
BasicComboBoxUI
扩展你照顾,你必须使用反射来加载UI类,距今约
- (例如)的
WindowsComboBoxUI
子类不会在Linux上加载
- 它不会与L- &工作FS(例如MacOS的?)不扩展
BasicComboBoxUI
- 它使有关
ListCellRenderer
假设可能并不总是保证
我仍然接受更清洁的解决方案。
class FastBasicComboBoxUI extends BasicComboBoxUI {
@Override
public void installUI(JComponent c) {
super.installUI(c);
Object prototypeValue = this.comboBox.getPrototypeDisplayValue();
if (prototypeValue != null) {
ListCellRenderer renderer = comboBox.getRenderer();
Component rendererComponent = renderer
.getListCellRendererComponent(this.listBox,
prototypeValue, 0, false, false);
if (rendererComponent instanceof JLabel) {
// Preferred size of the renderer itself is (-1,-1) at this point,
// so we need this hack
Dimension prototypeSize = new JLabel(((JLabel) rendererComponent)
.getText()).getPreferredSize();
this.listBox.setFixedCellHeight(prototypeSize.height);
this.listBox.setFixedCellWidth(prototypeSize.width);
}
}
}
}
我仍然接受更清洁的解决方案。
后来
事实证明这只是解决了一些问题。包含大量项目的组合框的初始显示仍然很慢。我必须确保弹出列表框立即通过将代码移动到ComboPopup
本身获得固定的单元大小,如下所示。请注意,如上所述,这取决于原型值。
@Override
protected ComboPopup createPopup() {
return new BasicComboPopup(comboBox) {
@Override
protected JList createList() {
JList list = super.createList();
Object prototypeValue = comboBox.getPrototypeDisplayValue();
if (prototypeValue != null) {
ListCellRenderer renderer = comboBox.getRenderer();
Component rendererComponent = renderer
.getListCellRendererComponent(list, prototypeValue, 0, false, false);
if (rendererComponent instanceof JLabel) {
// Preferred size of the renderer itself is (-1,-1) at this point,
// so we need this hack
Dimension prototypeSize = new JLabel(((JLabel) rendererComponent)
.getText()).getPreferredSize();
list.setFixedCellHeight(prototypeSize.height);
list.setFixedCellWidth(prototypeSize.width);
}
}
return list;
}
};
}
在我的小见解中,除了表现之外,我会担心用户体验。如果组合框中可能有数千个项目,那么也许是时候尝试将它们分类(并有第二个组合框),或让另一个组件找到您的值。你有一个“找到你键入”的方法,也许你应该有一个专门的组件,从不显示整个列表,只有一个过滤视图。它也将解决性能问题。 – Gnoupi 2010-07-07 13:22:27
@mcandre,如果我想要我的散文风格的建议,我不会来堆栈溢出。相同的JComboBox可能有一个项目或零。一个典型的数字是十。 “可能会有”不是多余的,它是准确的。 – 2010-07-08 07:16:22