获取IStructuredSelection(eclipse-rcp)的父级?

时间:2009-05-29 22:32:44

标签: java eclipse swt eclipse-rcp

我在视图中有一个TreeViewer,需要获取所选项目的父级(如果存在)。似乎没有什么工作,谷歌没有答案..

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 个答案:

答案 0 :(得分:7)

您可以从ITreeSelection获取父级。例如。

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
    }
}

答案 1 :(得分:4)

您还可以从树内容提供商处获取父级:

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);