TreeViewer is the foundation behind most trees and tree tables found in Eclipse. It provides excellent extensibility and options for customization. One feature, in-place editing of tree nodes, is very useful -- however the default implementation activates editing on the first click. This can be frustrating and unintuitive to users who expect the first click to select a node, and the second click to edit. This tip shows a simple way to cause TreeViewer to require two clicks to edit.

Since Eclipse 3.3, ColumnViewerEditorActivationStrategy has been available as API to configure how a TreeViewer starts editing. Our strategy will require the tree's current selection to be the node being clicked in order for a click to be considered an editing event. We do this by extending ColumnViewerEditorActivationStrategy as follows:


/**
* an activation strategy that only allows editor activation if the item under the
* event was already selected. This has the effect of requiring a click to first select
* the item, then a second click to edit.
*/
class SecondClickColumnViewerEditorActivationStrategy extends
ColumnViewerEditorActivationStrategy implements ISelectionChangedListener {

private Object selectedElement;

public SecondClickColumnViewerEditorActivationStrategy(ColumnViewer viewer) {
super(viewer);
viewer.addSelectionChangedListener(this);
}

@Override
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
IStructuredSelection selection = (IStructuredSelection)getViewer().getSelection();

return selection.size() == 1 && super.isEditorActivationEvent(event) &&
selectedElement == selection.getFirstElement();
}

public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection ss = (IStructuredSelection) event.getSelection();

if (ss.size() == 1) {
selectedElement = ss.getFirstElement();
return;
}

selectedElement = null;
}

}

This code relies on the order of events when comparing the tree's current selection against it's previous current selection.

Now all we have to do is install the strategy on our TreeViewer:


viewer = new org.eclipse.jface.viewers.TreeViewer(parent,
SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
TreeViewerEditor.create(viewer,null,new SecondClickColumnViewerEditorActivationStrategy(viewer),
ColumnViewerEditor.DEFAULT);

Voila! We're done: our TreeViewer now edits on the second click instead of the first.