// Create the editor and set its attributes
final TreeEditor editor = new TreeEditor(tree);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;

// Add a key listener to the tree that listens for F2.
// If F2 is pressed, we do the editing
tree.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
// Make sure one and only one item is selected when F2 is pressed
if (event.keyCode == SWT.F2 && tree.getSelectionCount() == 1) {
// Determine the item to edit
final TreeItem item = tree.getSelection()[0];

// Create a text field to do the editing
final Text text = new Text(tree, SWT.NONE);
text.setText(item.getText());
text.selectAll();
text.setFocus();

// If the text field loses focus, set its text into the tree
// and end the editing session
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
item.setText(text.getText());
text.dispose();
}
});

// If they hit Enter, set the text into the tree and end the editing
// session. If they hit Escape, ignore the text and end the editing
// session
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
switch (event.keyCode) {
case SWT.CR:
// Enter hit--set the text into the tree and drop through
item.setText(text.getText());
case SWT.ESC:
// End editing session
text.dispose();
break;
}
}
});

// Set the text field into the editor
editor.setEditor(text, item);
}
}
});
}