Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree with checkboxes

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:

  1. there's additional whitespace above + below the checkbox; I'd like to keep it the same as a regular JTree.
  2. I would like to distinguish between clicking on the checkbox itself (which should attempt to toggle the checkbox) and clicking on the text associated with the checkbox (which should allow an event listener to interpret this as clicking on the corresponding tree node and take whatever action is appropriate)

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)

like image 361
Jason S Avatar asked Aug 03 '09 16:08

Jason S


1 Answers

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:

  • Simple: CheckBoxTreeSample
  • Complex: WatchEventsFrame

The latter example also has code for recursively toggling subtrees in response to boxes being checked or unchecked (see the treeNodesChanged method).

like image 106
ctrueden Avatar answered Oct 13 '22 10:10

ctrueden