views:

830

answers:

2

I have a TreeViewer in a view and need to get the parent (if it exists) of an item selected. Nothing seems to work and google yields no answers..

mBacktestTree.addDoubleClickListener(new IDoubleClickListener() {
          public void doubleClick(DoubleClickEvent event) {
       IWorkbenchPage page = getSite().getPage();
       TreeViewer tree = (TreeViewer) event.getSource();
       Object selectObject = ((IStructuredSelection) tree.getSelection()).getFirstElement();

// now how can I get the parent of selectObject?
+2  A: 

You can get the parent from an ITreeSelection. E.g.

public class DirectoryView extends ViewPart 
{
    public void createPartControl(Composite parent) 
    {
     TreeViewer treeViewer = new TreeViewer(parent);
     treeViewer.setContentProvider(new DirectoryProvider());
     treeViewer.setInput(new File(System.getProperty("user.home"))); 
     treeViewer.addDoubleClickListener(new IDoubleClickListener() 
     {                    
      public void doubleClick(DoubleClickEvent event) 
      {
       ITreeSelection selection = ((ITreeSelection)event.getSelection());
       System.out.println(selection.getPaths()[0].getParentPath().getLastSegment());
      }
     });
    } 

    class DirectoryProvider implements ITreeContentProvider
    {
     public Object[] getChildren(Object parentElement) 
     {
      File[] folders = ((File) parentElement).listFiles();
      return folders == null ? new File[0] : folders;
     }

     public Object getParent(Object element) 
     {
      return ((File) element).getParent();
     }

     public boolean hasChildren(Object element) 
     {
      return getChildren(element).length >0;
     }

     public Object[] getElements(Object inputElement) 
     {
      return getChildren(inputElement);
     }

     public void dispose() 
     {
      // ignore
     }

     public void inputChanged(Viewer viewer, Object oldInput, Object newInput) 
     {
      // ignore
     }
    }

    public void setFocus() 
    {
     // ignore
    }
}
Kire Haglin
This worked perfectly, and allowed me to get the parent with getFirstSegment() and the child with getLastSegment(). If there is no children then the first segment equals the last, or with a check like:selection.getPaths()[0].getPArentPath().getSegmentCount() > 1thanks!
A: 

You can also obtain the parent from your tree content provider:

mBacktestTree.addDoubleClickListener(new IDoubleClickListener() {
                    public void doubleClick(DoubleClickEvent event) {
                            IWorkbenchPage page = getSite().getPage();
                            TreeViewer tree = (TreeViewer) event.getSource();
                            Object selectObject = ((IStructuredSelection)tree.getSelection()).getFirstElement();

ITreeContentProvider tcp =tree.getContentProvider();
Object parent = tcp.getParent(selectObject);
hudsonb
Thanks again, also useful