如何在java swing中创建具有多项选择的下拉列表?
我知道 JList
和 JComboBox
。我需要 JList
提供的具有多重选择功能的组合框下拉功能。
这是因为列表的内容太大,无法使用简单的列表来显示。我还需要选择多个项目,否则我会满足于 JComboBox
。
有什么建议吗?
I'm aware of JList
and JComboBox
. I need the combo box drop down functionality with multiple selection functionality that JList
provides.
This is because the contents of the list are too huge to be displayed using a simple list. I also need to select multiple items, otherwise I would have been content with JComboBox
.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用多选时,最好使用列表而不是组合框。随着 GUI 习惯的发展,人们期望组合框是单选的,而列表则可以是单选的。
将
JList
放入JScrollPane
中。您可以调用 setVisibleRowCount(int ) 在JList
上指定一次应显示多少行。When using multi-select, it's better to use a list than a combo box. As GUI idioms go, people expect a combo box to be single select, whereas lists can be either.
Place the
JList
in aJScrollPane
. You can call setVisibleRowCount(int) on theJList
to specify how many rows at a time should be shown.您可以为组合框创建自定义单元格渲染器,并向该组件添加复选框,以便您可以选中和取消选中它们。你必须做这样的事情:
You can make a custom cell renderer for the combobox and add checkboxes to that components, so you can check and uncheck them. You have to make something like this:
如果您的数据具有分层特征,请考虑使用 NetBeans 的
Outline
组件,该组件在 宣布新的 Swing 树表并在此答案中。这是 API 的当前开发版本。If your data has a hierarchical character, consider NetBeans'
Outline
component, discussed in Announcing the new Swing Tree Table and in this answer. Here's the Current Development Version of the API.为了实现所描述的功能,我最终决定“滥用”
JMenuBar
并向其中添加几个JCheckBoxMenuItems
。 GUI 完全符合目的(至少对我来说),只是 ItemEvent 的处理可能会变得有点烦人。(最后,我在项目上定义了一些位逻辑,然后可能限制自己只处理一种类型的事件)
To achieve the described functionality, I finally decided to "abuse" the
JMenuBar
and add to it severalJCheckBoxMenuItems
. The GUI then perfectly fits the purpose (at least for me), it is just the handling of the ItemEvent that risks to become a bit annoying.(finally there, I defined some bit logic over the items, and then may restrict myself to handling only one type of event)