Search code examples
javaswingjlistjcheckbox

Cannot add checkbox to the JList


I'm very new to programming, and I can't add JCheckbox to the JList. There is no error but nothing is displayed.

JFrame f=new JFrame();
String[] labels={"a","b","c","d","e"};
JCheckBox[] ch=new JCheckBox[labels.length];

JList list=new JList();

for (int i = 0; i < labels.length; i++) {
    ch[i]=new JCheckBox("CheckBox"+i);
    list.add(ch[i]);
}

JScrollPane pane=new JScrollPane(list);
f.add(pane);
f.setVisible(true);

Solution

  • A JList renderer can draw a checkbox, but JList does not support a cell editor. Instead, consider a one-column JTable. The default renderer & editor for a column of type Boolean.class is a JCheckBox, for example.