Find Project locations in Project Explorer (Eclips

2020-04-30 16:43发布

问题:

I've added a button in the context menu to execute only when you right click in the Project Explorer window. I want to be able to grab each project in the Project Explorer window and grab the ProjectName and ProjectLocation and put that into an object by itself and return the new array of objects.

I can't find a way to access the information that I need.

plugin.xml

<extension point="org.eclipse.ui.menus">
    <menuContribution locationURI="popup:org.eclipse.ui.navigator.ProjectExplorer#PopupMenu">
      <command commandId="helloworld.sample"
        label="Hello World" style="push">
      </command>
    </menuContribution>
  </extension>
  <extension point="org.eclipse.ui.commands">
    <command defaultHandler="helloworld.handler.samplehandler"
      id="helloworld.sample" name="Sample">
    </command>
  </extension>

samplehandler.java

IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

IWorkbenchPart viewpart  = page.findView("org.eclipse.ui.navigator.ProjectExplorer");

Tree tree = (Tree) ((TreeViewer) viewpart.getSite().getSelectionProvider()).getControl(); 
TreeItem[] selTree = tree.getSelection();

I feel as though tree or selTree would have the information I want but I can't find it. Any help?

回答1:

Use the selection data from the selection provider:

IStructuredSelection sel =   
     (IStructuredSelection)viewpart.getSite().getSelectionProvider().getSelection(); 

Object selObj = sel.getFirstElement();

IProject project =
   (IProject)Platform.getAdapterManager().getAdapter(selObj, IProject.class);

... might return null if selection is not the project

String name = project.getName();

IPath location = project.getLocation();

To get all the projects use:

IWorkspace workspace = ResourcesPlugin.getPlugin().getWorkspace();

IProject [] projects = workspace.getRoot().getProjects();