如何在多个项目选择的java swing中创建一个下拉列表?

我知道JListJComboBox 。 我需要具有JList提供的多种选择function的combobox下拉function。

这是因为列表的内容太大而无法使用简单列表显示。 我还需要选择多个项目,否则我会满足于JComboBox

有什么建议么?

使用多选时,最好使用列表而不是combobox。 随着GUI隐喻的出现,人们期望combobox是单​​选的,而列表可以是。

列表的内容太大,无法使用简单列表显示

JList放在JScrollPane 。 您可以在JList上调用setVisibleRowCount(int)来指定一次应显示多少行。

您可以为combobox创建自定义单元格渲染器,并为该组件添加复选框,以便您可以选中和取消选中它们。 你必须做这样的事情:

 public class MyComboBoxRenderer implements ListCellRenderer { private String[] items; private boolean[] selected; public MyComboBoxRenderer(String[] items){ this.items = items; this.selected = new boolean[items.lenght]; } public Component getListCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int index) { // Create here a JLabel with the text // Create here a JCheckBox // Add them to a layoutmanager return this; } public void setSelected(int i, boolean flag) { this.selected[i] = flag; } } 

如果您的数据具有分层字符,请考虑NetBeans的Outline组件,在“ 公布新的Swing树表”和本答案中进行了讨论 。 这是API的当前开发版本

为了实现所描述的function,我最终决定“滥用” JMenuBar并添加几个JCheckBoxMenuItems 。 然后,GUI完全符合目的(至少对我来说),只是处理ItemEvent有可能变得有点烦人。

(最后在那里,我在项目上定义了一些逻辑,然后可能限制自己只处理一种类型的事件)