Java Reference
In-Depth Information
DefaultCellEditor Class
The
DefaultCellEditor
class serves as an editor for both tree nodes and table cells. The class
allows you to easily provide a text editor, combo box editor, or check box editor to modify the
contents of a node or cell.
The
DefaultTreeCellEditor
class, described next, uses this class to provide an editor for a
customized text field, maintaining the appropriate node-type icon based on a
TreeCellRenderer
.
Creating a DefaultCellEditor
When you create a
DefaultCellEditor
instance, you provide the
JTextField
,
JComboBox
, or
JCheckBox
to use as the editor.
public DefaultCellEditor(JTextField editor)
JTextField textField = new JTextField();
TreeCellEditor editor = new DefaultCellEditor(textField);
public DefaultCellEditor(JComboBox editor)
public static void main (String args[]) {
JComboBox comboBox = new JComboBox(args);
TreeCellEditor editor = new DefaultCellEditor(comboBox);
...
}
public DefaultCellEditor(JCheckBox editor)
JCheckBox checkBox = new JCheckBox();
TreeCellEditor editor = new DefaultCellEditor(checkBox);
With a
JTree
, you should use the
DefaultTreeCellEditor
if you want a
JTextField
editor.
That text field will share the same font and use the appropriate editor border for the tree. When
a
JCheckBox
is used as the editor, the node for the tree should be either a
Boolean
value or a
String
that can be converted to a
Boolean
. (If you are unfamiliar with conversion from
String
to
Boolean
, see the Javadoc for the
Boolean
constructor that accepts a
String
.)
After creating an editor, you tell the tree to use it with a call similar to
tree.
setCellEditor(editor)
. And don't forget to make the tree editable with
tree.
setEditable(true)
. For instance, if you wanted an editable combo box as your editor,
the following source code would work:
JTree tree = new JTree(...);
tree.setEditable(true);
String elements[] = { "Root", "chartreuse", "rugby", "sushi"} ;
JComboBox comboBox = new JComboBox(elements);
comboBox.setEditable(true);
TreeCellEditor editor = new DefaultCellEditor(comboBox);
tree.setCellEditor(editor);
This code produces the screen shown in Figure 17-13 when editing the
basketball
node.
Notice that there is no icon to indicate the type of node being edited. This is rectified with the