我相信使用公共API进行此操作的唯一方法是编写自定义UI(有两个
bug可以解决此问题)。
如果您只想要一些简单的东西,我发现了这种使用实现细节的方法(在此处):
public void popupMenuWillBecomeVisible(PopupMenuEvent e) { JComboBox box = (JComboBox) e.getSource(); Object comp = box.getUI().getAccessibleChild(box, 0); if (!(comp instanceof JPopupMenu)) return; JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0); Dimension size = new Dimension(); size.width = box.getPreferredSize().width; size.height = scrollPane.getPreferredSize().height; scrollPane.setPreferredSize(size); // following line for Tiger // scrollPane.setMaximumSize(size);}把
PopupMenuListener它
放进 去, 可能 对你有用。
或者,您可以使用第一个链接的bug中的代码:
class StyledComboBoxUI 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; }}class StyledComboBox extends JComboBox { public StyledComboBox() { setUI(new StyledComboBoxUI()); }}


