Custom Java ListCellRenderer - Can't click JCheckBox

穿精又带淫゛_ 提交于 2019-12-25 04:53:56

问题


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


回答1:


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)));



回答2:


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.



来源:https://stackoverflow.com/questions/2833070/custom-java-listcellrenderer-cant-click-jcheckbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!