JTree with checkboxes

后端 未结 4 2068
温柔的废话
温柔的废话 2020-12-05 19:58

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.

4条回答
  •  遥遥无期
    2020-12-05 20:42

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

提交回复
热议问题