来自代码分支和太阳论坛,我知道为JComboBox设置水平滚动条的技术。
然而,他们建议的解决方案局限于外观特定。
正如你所看到的,如果用户在带有GTK+look n feel的Linux机器下,或者在带有Nimbus look n fell的Windows机器下,下面的关键代码片段将不能很好地工作。
我如何才能有一种可移植的方式,使JComboBox能够有一个水平滚动条?
完整的源代码是AutoCompleteJComboBox.java
关键代码片段如下:
package org.yccheok.jstock.gui;
public class AutoCompleteJComboBox extends JComboBox {
@Override
public void setUI(ComboBoxUI ui)
{
if (ui != null)
{
// Let s try our own customized UI.
Class c = ui.getClass();
final String myClass = "org.yccheok.jstock.gui.AutoCompleteJComboBox$My" + c.getSimpleName();
try {
ComboBoxUI myUI = (ComboBoxUI) Class.forName(myClass).newInstance();
super.setUI(myUI);
return;
} catch (ClassNotFoundException ex) {
log.error(null, ex);
} catch (InstantiationException ex) {
log.error(null, ex);
} catch (IllegalAccessException ex) {
log.error(null, ex);
}
}
// Either null, or we fail to use our own customized UI.
// Fall back to default.
super.setUI(ui);
}
// This is a non-portable method to make combo box horizontal scroll bar.
// Whenever there is a new look-n-feel, we need to manually provide the ComboBoxUI.
// Any idea on how to make this portable?
//
protected static class MyWindowsComboBoxUI extends com.sun.java.swing.plaf.windows.WindowsComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
protected static class MyMotifComboBoxUI extends com.sun.java.swing.plaf.motif.MotifComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
protected static class MyMetalComboBoxUI extends javax.swing.plaf.metal.MetalComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
private static class MyComboPopup extends BasicComboPopup
{
public MyComboPopup(JComboBox combo)
{
super(combo);
}
@Override
public JScrollPane createScroller()
{
return new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
}
}