本文介绍了如何更改JComboBox下拉列表的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个可编辑的 JComboBox ,其中包含单字母值的列表。因为组合框很小。I have an editable JComboBox which contains a list of single letter values. Because of that the combobox is very small.每个字母都有特殊的含义,有时在用户很少使用字母的情况下不清楚。因为我创建了一个自定义 ListCellRenderer ,它显示了下拉列表中每个字母的含义。Every letter has a special meaning which sometimes isn't clear to the user in case of rarely used letters. Because of that I've created a custom ListCellRenderer which shows the meaning of each letter in the dropdown list.不幸的是,此解释不适合下拉列表,因为它的宽度与组合框的宽度相同。Unfortunately this explanation doesn't fit into the dropdown because it is to small, because it has the same width as the combobox.有什么办法让下拉列表比组合框宽吗?Is there any way to make the dropdown list wider than the combobox?这是我想要实现的: ---------------------| Small JCombobox | V | --------------------------------------------| "Long item 1" | --------------------------------------------| "Long item 2" | --------------------------------------------| "Long item 3" | --------------------------------------------我无法更改组合框的宽度,因为应用程序是一个旧的旧应用程序的休闲,有些事情正如他们以前。 (在这种情况下,组合框必须随时保持小尺寸)I cannot change the width of the combobox because the application is a recreation of an old legacy application where some things have to be exactly as they were before. (In this case the combobox has to keep it's small size at all costs)推荐答案我相信唯一的方法公共API是写自定义UI(有两个 错误处理此问题)。I believe the only way to do this with the public API is to write a custom UI (there are two bugs dealing with this).如果你只是想要一些快速和脏,我发现这种方式使用实现细节这样做(此处):If you just want something quick-and-dirty, I found this way to use implementation details to do it (here):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 > 。或者您可以使用 first linked 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()); }} 这篇关于如何更改JComboBox下拉列表的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-13 15:12