我知道
JList
和JComboBox
。我需要 JList
提供的具有多重选择功能的组合框下拉功能。
这是因为列表的内容太大,无法使用简单的列表来显示。我还需要选择多个项目,否则我就满足了
JComboBox
。
有什么建议吗?
使用多选时,最好使用列表而不是组合框。随着 GUI 习惯的发展,人们期望组合框是单选的,而列表则可以是单选的。
列表内容太大,无法用简单的列表显示
将
JList
放入 JScrollPane
中。您可以在 JList
上调用 setVisibleRowCount(int)来指定一次应显示多少行。
您可以为组合框创建自定义单元格渲染器,并向该组件添加复选框,以便您可以选中和取消选中它们。你必须做这样的事情:
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;
}
}
为了实现所描述的功能,我最终决定“滥用”
JMenuBar
并添加几个JCheckBoxMenuItems
。 GUI 完全符合目的(至少对我来说),只是 ItemEvent 的处理可能会变得有点烦人。
(最后,我在项目上定义了一些位逻辑,然后可能限制自己只处理一种类型的事件)