javaswttreeviewer

Adding double-click expansion to the Tree Viewer in SWT


Double-Clicking tree items works completely fine, but when I press CTRL + M on the keyboard then the tree items expand\collapse, can someone please tell me the reason behind this? Is this a bug in Eclipse or why does this double-click functionality get triggered when I press CTRL+M.

Thanks.


Solution

  • Use TreeViewer.addDoubleClickListener to listen for tree double clicks not a mouse listener. You could use something like this:

    private class DoubleClickListener implements IDoubleClickListener
    {
      @Override
      public void doubleClick(final DoubleClickEvent event)
      {
        final IStructuredSelection selection = (IStructuredSelection)event.getSelection();
        if (selection == null || selection.isEmpty())
          return;
    
        final Object sel = selection.getFirstElement();
    
        final ITreeContentProvider provider = (ITreeContentProvider)treeViewer.getContentProvider();
    
        if (!provider.hasChildren(sel))
          return;
    
        if (treeViewer.getExpandedState(sel))
          treeViewer.collapseToLevel(sel, AbstractTreeViewer.ALL_LEVELS);
        else
          treeViewer.expandToLevel(sel, 1);
      }
    }
    

    Update: Using TreeViewer.addDoubleClickListener is the preferred way to do double click handling for all classes derived from StructuredViewer.

    Each double click listener is run using SafeRunnable which deals with any exceptions that the listener may throw, this safeguards the rest of the code for errors in the listeners.

    The DoubleClickEvent provides direct access to the model object data so it is not necessary to deal with Tree or TreeItem objects to work out selections.

    The double click code in the TreeViewer interfaces correctly with the OpenStrategy single / double click to open code.