views:

216

answers:

2

Made a custom ListCellRenderer:

import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

/**
 *
 * @author Spencer
 */
public class TaskRenderer implements ListCellRenderer {

    private Task task;

    private JPanel panel = new JPanel();
    private JCheckBox checkbox = new JCheckBox();
    private JLabel label = new JLabel();

    public TaskRenderer() {
        panel.add(checkbox);
        panel.add(label);
    }

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        task = (Task) value;
        label.setText(task.getName());
        return panel;
    }

}

Have a JList with each cell in it rendered using the above class, but the checkboxes in the panels for each cell cannot be clicked. Thought it had to do with it not getting focus. Any ideas?

Thanks, Spencer

+2  A: 

Your custom renderer is simply governing the appearance of the JList contents, not adding any functionality such as the ability to modify the components (check box) - Imagine it simply as a rubber stamp used to display each list cell in turn.

I'd recommend solving the problem by:

  1. Use a single-column JTable instead of a JList.
  2. Define a bespoke TableModel implementation by sub-classing AbstractTableModel and override getColumnClass(int) to return Boolean.class for column 0. Note that the default renderer will now render this as a JCheckBox. However, it will not be a labelled JCheckBox as you require.
  3. Add a bespoke TableCellRenderer for Booleans; e.g. myTable.setCellRenderer(Boolean.class, new MyLabelledCheckBoxRenderer());
  4. Add an editor for Booleans, using something similar to: myTable.setCellEditor(Boolean.class, new DefaultEditor(new JCheckBox("Is Enabled)));
Adamski
A: 

JIDE Common Layer has a GPL'ed CheckBoxList. Basically it uses a JPanel as cell renderer with a JCheckBox in front of another renderer (which you can set yourself), and handles mouse/key events.

If you really want to stick to your JCheckBox renderer, you can listen to mouse/key events and process them appropriately. Keep in mind that, as Adamski pointed out, cell renderer is a rubber stamp (Swing 101) so you have to always set the check box selected state in getListCellRendererComponent(), otherwise all your checkboxes will have the save state.

Geoffrey Zheng