Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

The Cell Editor

Constructing the cell editor is also a simple matter—all we need is an editor that displays a combo box containing the list of hardware items that can appear in the tree. The combo box itself can be created by calling the Tree-Model's getNamesAsCombo method. Therefore, creating and installing a suitable editor requires only four lines of code:

// Define a replacement editor 
JComboBox combo = m.getNamesAsCombo();
DefaultCellEditor comboEditor =
                  new DefaultCellEditor(combo);
DefaultTreeCellEditor editor =
        new DefaultTreeCellEditor(t, r, comboEditor);
t.setCellEditor(editor); 

The basic editor is created by wrapping the combo with a standard DefaultCellEditor, which is then wrapped in a DefaultTreeCellEdi-tor to make it behave suitably within a JTree. In this code extract, the variable r refers to the custom cell renderer for the tree that will be discussed next. Even though the editing process requires a certain amount of clever handling to arrange for the String from the combo box to be converted to the correct HardwareObject to be installed in the node, none of this complication is visible to the editor because it is all implemented in the Tree-Model. Therefore, it is perfectly acceptable to use a standard editor.

  • + Share This
  • 🔖 Save To Your Account