javaswingjcheckbox

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


What would be the best way to have a list of items with a checkbox each in Java Swing?

I.e. a JList with items that have some text and a checkbox each?


Solution

  • Create a custom ListCellRenderer and asign it to the JList.

    This custom ListCellRenderer must return a JCheckbox in the implementantion of getListCellRendererComponent(...) method.

    But this JCheckbox will not be editable, is a simple paint in the screen is up to you to choose when this JCheckbox must be 'ticked' or not,

    For example, show it ticked when the row is selected (parameter isSelected), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the ListModel, but then is up to you to implement the method who changes the check status of the data, and notify the change to the JList to be repainted.

    I Will post sample code later if you need it

    ListCellRenderer