如何将另一个 LayoutManager 应用于 JComboBox? (多列JComboBox尝试)
我正在尝试制作一个多列 JComboBox。我环顾四周,这似乎是一件非常棘手的事情。除非很多人,否则我对拥有一个表格(在其中选择一行)不感兴趣:我需要消除 JComboBox 中的滚动条,为了实现这一点,我想将其项目放在多列中列出而不是仅将它们放在一列中。
到目前为止,我最好的选择是这样做:
JComboBox dropdown = new JComboBox(validValues);
CellRendererPane crp = (CellRendererPane) dropdown.getComponent(1);
crp.setLayout(new GridLayout(4, 4)); // for 16 items...
但这不起作用。它仍然将单元格放置在一列中。我尝试在设置 LayoutManager 后添加项目,但这并不影响结果。
任何人都知道如何实现这一目标?
到目前为止,我认为 ListCellRenderer 没什么用处。它仅指定如何绘制一个单元格(一次一个),而不指定如何放置所有单元格(它们彼此之间的相对位置是什么)。
欢迎任何帮助!
谢谢!
乔丹
I'm trying to make a multi-column JComboBox. I've looked around quite a bit and it seems to be a very tricky thing to do. Unless many people, I'm not interested in having a table (where you select a row): I need to eliminate the scroll bar in the JComboBox and, in order to achieve this, I want to lay its items in a multi-column list instead of having them in only one column.
My best bet so far was to do this:
JComboBox dropdown = new JComboBox(validValues);
CellRendererPane crp = (CellRendererPane) dropdown.getComponent(1);
crp.setLayout(new GridLayout(4, 4)); // for 16 items...
But it doesn't work. It still lays cells in a single column. I tried adding items after setting the LayoutManager, but it doesn't affect the result.
Anyone has a clue about how to achieve this?
So far, I've seen the ListCellRenderer as useless to play with. It only specifies how to draw a cell (one at a time), not how to lay all of them (what is their relative position to each other).
Any help is welcome!
Thanks!
MJ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
组合框使用 JList 来呈现弹出窗口中的项目。默认情况下,每个项目显示在一行中。您可以直接使用以下命令访问此列表:
现在您可以访问该列表,您应该可以使用以下命令更改默认显示:
希望当达到下拉列表的宽度时,这些项目将换行。下拉列表的宽度由组合框的宽度控制,因此您可能需要使用以下方法来调整组合框的宽度:
编辑:
实际上,忘记使用 setPrototypeDisplayValue(...),我认为您需要手动设置弹出窗口的大小。
默认情况下,弹出窗口的宽度始终等于组合框的宽度。您可以通过使用 PopupMenuListener 来覆盖弹出窗口的大小来修改此行为。要开始使用,您可以查看组合框弹出窗口入口。您的代码将变得更加简单,因为您所需要做的就是对弹出窗口的所需宽度进行硬编码。
A combobox uses a JList to render the items in a popup. By default each item is displayed in a single row. You can access this list directly using:
Now that you have acess to the list you should be able to change the default display by using:
Hopefully the items will now wrap when the width of the dropdown is reached. The width of the dropdown is controlled by the width of the combo box so you may need to play with the width of the combo box by using:
Edit:
Actually, forget about using setPrototypeDisplayValue(...), I think you will need to manually set the size of the popup.
By default the width of the popup is always equal to the width of the combo box. You can modify this behaviour by using a PopupMenuListener to override the size of the popup. To get you started you can look at the Combo Box Popup entry. Your code will be much simpler since all you will need to do is hardcode the desired width of your popup.