I already have a checkbox in a Java Swing TreeNode. But how do I make it checkable?

165 views Asked by At

Note: I am NOT asking how to put a checkbox in a JTree - previously, a confused moderator thought this is what I was asking. I already have the checkbox in the tree. I am asking what class or method controls the checkability of the checkbox...

In order to get a checkbox inside a Tree node, I read that you had to make a checkbox renderer, so I made one:

class CheckboxCellRenderer implements TreeCellRenderer {
    final static Logger logger = LoggerFactory.getLogger(CheckboxCellRenderer.class);
    JLabel firstNameLabel = new JLabel(" ");

    JPanel renderer = new JPanel();

    JCheckBox checkbox;

    DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

    public CheckboxCellRenderer() {

        super();
        checkbox = new JCheckBox(firstNameLabel.getText(), false);
        renderer.add(checkbox);
        renderer.add(firstNameLabel);

    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
            boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Component returnValue = null;
        firstNameLabel.setText(value.toString());
        if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
            Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
            renderer.setEnabled(tree.isEnabled());
            if(((DefaultMutableTreeNode) value).getLevel()==1){
                returnValue = renderer;
            }
        }
        if (returnValue == null) {
            returnValue = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        }

        return returnValue;
    }
}

This creates the checkbox in the tree node. But for some reason this makes the checkbox uncheckable, and nothing happens when I click it. Why does creating the checkbox in the renderer "break" the checkbox? How do I make the checkbox checkable (i.e. it gets checked when I click the checkbox, and unchecked when I click it again)?

1

There are 1 answers

0
john smith On

In order to be make a checkbox "checkable", it looks like you need an editor class. This can be demonstrated by commenting out the line "tree.setCellEditor(new CheckBoxNodeEditor(tree));" in the "CheckBox Node Tree Sample" that Abra posted, which makes the example "uncheckable".