3

我在视图中有一个 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?
4

2 回答 2

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
    }
}
于 2009-05-30T08:24:15.757 回答
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);
于 2009-08-28T14:12:04.993 回答