问题
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
回答1:
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:
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
Now that you have acess to the list you should be able to change the default display by using:
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
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:
list.setPrototypeDisplayValue(....);
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.
来源:https://stackoverflow.com/questions/5225025/how-to-apply-another-layoutmanager-to-a-jcombobox-multi-column-jcombobox-attem