Java Reference
In-Depth Information
Listing 17-9. Custom Node Data for a JTree
public class CheckBoxNode {
String text;
boolean selected;
public CheckBoxNode(String text, boolean selected) {
this.text = text;
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean newValue) {
selected = newValue;
}
public String getText() {
return text;
}
public void setText(String newValue) {
text = newValue;
}
public String toString() {
return getClass().getName() + "[" + text + "/" + selected + "]";
}
}
Creating the CheckBoxNodeRenderer Class
The renderer will have two parts. For nonleaf nodes, you can use the DefaultTreeCellRenderer
because those nodes aren't meant to be CheckBoxNode elements. For the renderer for leaf nodes
of type CheckBoxNode , you need to map the data structure into an appropriate renderer. Because
these nodes contain a selection state and a text label, the JCheckBox acts as a good renderer for
the leaf nodes.
The easier of the two to explain is the nonleaf node renderer. In this example, it simply
configures a DefaultTreeCellRenderer as it would normally; nothing special is done.
The renderer for the leaf nodes requires a bit more work. Before even configuring any nodes,
you need to make it look like the default renderer. The constructor acquires the necessary fonts
and various colors from the look and feel for the renderer, ensuring that the two renderers will
appear similar.
The definition for the tree cell renderer, class CheckBoxNodeRenderer , is shown in Listing 17-10.
Search WWH ::




Custom Search