JTree delegates node rendering to a renderer. All renderers are instances of the TreeCellRenderer interface, which defines a single method, getTreeCellRendererComponent , as follows :
public Component getTreeCellRendererComponent (JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus);
You can create a custom tree cell renderer by implementing the TreeCellRenderer interface, or use the DefaultTreeCellRenderer class, which provides a default implementation for TreeCellRenderer . When a new JTree is created, an instance of DefaultTreeCellRenderer is assigned to the tree renderer. The DefaultTreeCellRenderer class maintains three icon properties named leafIcon , openIcon , and closedIcon for leaf nodes, expanded nodes, and collapsed nodes. It also provides colors for text and background. The following code sets new leaf, open and closed icons, and new background selection color in the tree:
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTree1.getCellRenderer(); renderer.setLeafIcon(yourCustomLeafImageIcon); renderer.setOpenIcon(yourCustomOpenImageIcon); renderer.setClosedIcon(yourCustomClosedImageIcon); renderer.setBackgroundSelectionColor(Color.red);
Note
The default leaf, open icon, and closed icon are dependent on the look-and-feel. For instance, on Windows look-and-feel, the open icon is -, and the closed icon is +. |
JTree comes with a default cell editor. If JTree 's editable property is true , the default editor activates a text field for editing when the node is clicked three times. By default, this property is set to false . To create a custom editor, you need to extend the DefaultCellEditor class, which is the same class you used in table cell editing. You can use a text field, a check box, or a combo box, and pass it to DefaultCellEditor 's constructor to create an editor. The following code uses a combo box for editing colors. The combo box editor is shown in Figure 31.28(a).
// Customize editor JComboBox jcboColor = new JComboBox(); jcboColor.addItem( "red" ); jcboColor.addItem( "green" ); jcboColor.addItem( "blue" ); jcboColor.addItem( "yellow" ); jcboColor.addItem( "orange" ); jTree1.setCellEditor( new javax.swing.DefaultCellEditor(jcboColor)); jTree1.setEditable( true );
There are two annoying problems with the editor created in the preceding code. First, it is activated with just one mouse click. Second, it overlaps the node's icon, as shown in Figure 31.28(a). These two problems can be fixed by using the DefaultTreeCellEditor , as shown in the following code:
jTree1.setCellEditor ( new javax.swing.tree.DefaultTreeCellEditor(jTree1, new javax.swing.tree.DefaultTreeCellRenderer(), new javax.swing.DefaultCellEditor(jcboColor)));
The new editor is shown in Figure 31.28(b). Editing using DefaultTreeCellEditor starts on a triple mouse click. The combo box does not overlap the node's icon.