How do I make a list with checkboxes in Java Swing?

A wonderful answer is this CheckBoxList. It implements Telcontar’s answer (though 3 years before :)… I’m using it in Java 1.6 with no problems. I’ve also added an addCheckbox method like this (surely could be shorter, haven’t used Java in a while):

public void addCheckbox(JCheckBox checkBox) {
    ListModel currentList = this.getModel();
    JCheckBox[] newList = new JCheckBox[currentList.getSize() + 1];
    for (int i = 0; i < currentList.getSize(); i++) {
        newList[i] = (JCheckBox) currentList.getElementAt(i);
    }
    newList[newList.length - 1] = checkBox;
    setListData(newList);
}

I tried out the demo for the Jidesoft stuff, playing with the CheckBoxList I encountered some problems (behaviors that didn’t work). I’ll modify this answer if I find problems with the CheckBoxList I linked to.

Leave a Comment