我正在寻找一种方法来改变 JComboBox 弹出窗口的宽度。基本上,弹出窗口应该与最宽的组合框条目一样宽,而不是当前组合框的宽度。
我知道如何实现这一点的唯一方法是创建 ComboBoxUI 的自定义实例并将其设置在 JComboBox 上(示例代码演示了目标:顶部组合框显示宽弹出窗口,底部是默认行为)。然而,由于它替换了 ComboBox 的 UI,它在某些 L&F 上可能看起来很奇怪(例如,对于 WinXP Luna 主题,ComboBox 看起来像 Classic 主题)。
有没有办法以与 L&F 无关的方式实现这种行为?
public class CustomCombo extends JComboBox {
final static class CustomComboUI extends BasicComboBoxUI {
protected ComboPopup createPopup() {
BasicComboPopup popup = new BasicComboPopup(comboBox) {
@Override
protected Rectangle computePopupBounds(int px, int py, int pw, int ph) {
return super.computePopupBounds(px, py, Math.max(
comboBox.getPreferredSize().width, pw), ph);
}
};
popup.getAccessibleContext().setAccessibleParent(comboBox);
return popup;
}
}
{
setUI(new CustomComboUI());
}
public static void main(String[] argv) {
try {
final String className = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(className);
} catch (final Exception e) {
// ignore
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public static void createGUI() {
JComboBox combo1 = new CustomCombo();
JComboBox combo2 = new JComboBox();
JPanel panel = new JPanel();
JFrame frame = new JFrame("Testframe");
combo1.addItem("1 Short item");
combo1.addItem("2 A very long Item name that should display completely in the popup");
combo1.addItem("3 Another short one");
combo2.addItem("1 Short item");
combo2.addItem("2 A very long Item name that should display completely in the popup");
combo2.addItem("3 Another short one");
panel.setPreferredSize(new Dimension(30, 50));
panel.setLayout(new GridBagLayout());
GridBagConstraints gc;
gc = new GridBagConstraints(0, 0, 1, 1, 1D, 0D, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
panel.add(combo1, gc);
gc = new GridBagConstraints(0, 1, 1, 1, 1D, 0D, GridBagConstraints.WEST,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
panel.add(combo2, gc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}