JcomboBox multiple selection

那年仲夏 提交于 2020-01-02 01:30:28

问题


I have a jcombobox in my application. and i want it to support multiple selection (like it do in a jlist). is there any code example?


回答1:


I think it's not possible, unless you use a JList, like you said.

The JComboBox API reports:

The user can select a value from the drop-down list, which appears at the user's request.

And a JComboBox tutorial:

Lists are not terribly attractive, but they're more appropriate than combo boxes when the number of items is large (say, over 20) or when selecting multiple items might be valid.

Update:

I reviewed this answer, because actually it's "possible" to do that using a ListCellRenderer, adding a checkbox to each item. Please consider this answer to implement this "solution".

However, I don't think it's a good idea for the following reasons:

  1. there's a control like a JList that allows multiple selection;
  2. a JComboBox control is designed just for single item selection;
  3. it doesn't make sense to me to still use a JComboBox control and allow a multiple selection.



回答2:


It's not quite impossible but there's a lot of work to do to get the job done. You'll need to create your own classes to extend/implement all of these:

  • ListCellRenderer (so you can mark the selected items when the popup is showing and indicate (at least) that there are multiple selections when it is not).
  • JComboBox (obviously)
  • BasicComboBoxUI (this is actually where most of the work is)
  • BasicListUI (at least I had to)
  • ComboBoxModel
And you'll need to develop your own class that implements ItemListener, MouseListener, PopupMenuListener, MouseMotionListener, PropertyChangeListener, KeyListener, ListSelectionListener.
Hint: you'll need to override a lot of createXXXListener() methods in the UI classes in order to bypass the many places where multiple selections are discarded.
[And it still doesn't allow for an editable multi-selection combo.]

来源:https://stackoverflow.com/questions/8471553/jcombobox-multiple-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!