I need to add checkboxes to a JTree. A custom TreeCellRenderer/TreeCellEditor seems like the right approach. So far I used the CheckBoxNodeRenderer approach in this webpage.
I have released a standalone Swing Checkbox Tree project, available from Maven Central as org.scijava:swing-checkbox-tree
.
The package is based on John Zukowski's CheckBox Node Tree Sample code. It is BSD-2-licensed with no dependencies.
It allows mixing and matching of DefaultMutableTreeNode
and CheckBoxNodeData
node types. It also allows check box nodes as non-leaf nodes.
Regarding the question's issue #1: I did not test on all platforms, but on my OS X systems, the CheckBoxNodeData
nodes are exactly the same height in pixels as the DefaultMutableTreeNode
nodes.
Regarding the question's issue #2: it uses a JCheckBox
+ JLabel
in a JPanel
(as aperkins suggests) to differentiate between clicking on a check box (to check/uncheck a node) versus a label (to select a node).
Example usages:
The latter example also has code for recursively toggling subtrees in response to boxes being checked or unchecked (see the treeNodesChanged
method).