The CheckBox tree is a very common UI component that makes it easy for users to check nodes in the trees by specific rules. In this paper, a simple checking rule is implemented: When a node is checked, all subordinate nodes of the node are checked, and all subordinate nodes of the node are unchecked when a node is unchecked. (Last updated in 2009.08.05)
A common way to implement a checkbox tree is to use Jcheckbox as a jtree treecellrendrer and to implement a specific checking rule to check/uncheck a checkbox.
1. Tree node
Defaultmutabletreenode is the most commonly used TreeNode implementation, where we will extend this implementation--checkboxtreenode and add a property ischecked to identify whether the node is to be checked. The complete code for the class is as follows:
public class CheckBoxTreeNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 3195314943599939279L;
private boolean isChecked = false;
public CheckBoxTreeNode(Object userObject) {
super(userObject);
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
2. Render Device
As described at the beginning of this article, we will use Jcheckbox as the renderer for the tree node presentation, while determining the rules for checking or canceling the nodes. Checkboxtreecellrenderer itself is a jcheckbox, then in the implementation of the Gettreecellrenderercomponent method, simply return its own instance, and for the check or cancel the selection of conditions, is determined by the IsChecked property in Checkboxtreenode, the complete code looks like this:
public class Checkboxtreecellrenderer extends Jcheckbox implements Treecellrenderer {
private static Final long serialversionuid = -6432020851855339311l;
Public Checkboxtreecellrenderer () {
Setopaque (false);
Public Component gettreecellrenderercomponent (jtree tree, Object value,
Boolean Selected, Boolean expanded, Boolean leaf, int row,
Boolean hasfocus) {
Che Ckboxtreenode node = ((checkboxtreenode) value); Gets the tree node object.
SetText (node.tostring ());//Set the text displayed by the checkbox.
//When the tree node is set to tick, the checkbox corresponding to the node is checked, or uncheck.
if (node.ischecked ()) {
setselected (true);
Setforeground (Color.Blue);
} else {
setselected (false);
Setforeground (Tree.getforeground ());
return this;
}
}