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. It works OK except for two things:
is there a way to do these things? I looked around for JTrees with checkboxes, can't find much. JIDE looks good but I need to use free open-source software (GPL is not ok, LGPL is ok) in this case. (or create my own checkbox tree)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With