Java Reference
In-Depth Information
JComboBox comboBox = new JComboBox(args);
TreeCellEditor comboEditor = new DefaultCellEditor(comboBox);
TreeCellEditor editor = new DefaultTreeCellEditor(tree, renderer, comboEditor);
...
}
Creating a Proper ComboBox Editor for a Tree
As Figure 17-13 showed, using a JComboBox as the TreeCellEditor via a DefaultCellEditor
doesn't place the appropriate node-type icon next to the editor. If you want the icons present,
you need to combine the DefaultCellEditor with a DefaultTreeCellEditor to get an editor
with both an icon and an editor. It's really not as hard as it sounds. It just involves two extra
steps: getting the renderer for the tree (from which to get the icons), and then combining the
icon with the editor to get a new editor. The following source demonstrates this:
JTree tree = new JTree();
tree.setEditable(true);
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer();
String elements[] = { "Root", "chartreuse", "rugby", "sushi"} ;
JComboBox comboBox = new JComboBox(elements);
comboBox.setEditable(true);
TreeCellEditor comboEditor = new DefaultCellEditor(comboBox);
TreeCellEditor editor = new DefaultTreeCellEditor(tree, renderer, comboEditor);
tree.setCellEditor(editor);
The improved output is shown in Figure 17-15.
Figure 17-15. An editable JTree with a JComboBox editor and tree icons
Creating an Editor Just for Leaf Nodes
In some cases, you will want only the leaf nodes of a tree to be editable. Returning null from the
getTreeCellEditorComponent() request effectively makes a node not editable. Unfortunately,
this causes a NullPointerException to be thrown by the user interface class.
Instead of returning null , you can override the default behavior of the public boolean
isCellEditable(EventObject object) method, which is part of the CellEditor interface. If the
original return value is true , you can do an additional check to see if the selected node of the
tree is a leaf. Nodes of a tree implement the TreeNode interface (described later in this chapter
in the “TreeNode Interface” section ). This interface happens to have the method public
 
Search WWH ::




Custom Search