Search code examples
javaeclipse-plugineclipse-rcp

Programmatically selecting/expanding a folder resource in Project Explorer


In Eclipse RCP, I'm programmatically creating a resource (folder with files) inside a Project, I wish to select and expand the folder (I know its path) in the Project Explorer (assuming it's opened). The effect should be similar than that of the "Link with Editor" button, but here the resource is not to be opened in an editor.


Solution

  • First get the workbench page -

    In a view or editor use:

    IWorkbenchPage page = getSite().getPage();
    

    elsewhere use

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

    Find the view, the ProjectExplorer view id is given in IPageLayout.ID_PROJECT_EXPLORER

    IViewPart view = page.findView(IPageLayout.ID_PROJECT_EXPLORER);
    

    The project explorer view implements ISetSelectionTarget so you can do:

    ((ISetSelectionTarget)view).selectReveal(new StructuredSelection(object to show));
    

    or in Java 16 onwards use a instanceof type pattern:

    if (view instanceof ISetSelectionTarget setSel) {
       setSel.selectReveal(new StructuredSelection(object to show));
    }