Delacyr
Delacyr

Reputation: 16

How to select a specific node in a TreeViewer?

I built a treeviewer for a specific project, but now I need to select a specific item/node in this treeviewer.

To build the treeviewer, I did this:

viewer = new TreeViewer(composite);
viewer.getTree().setLayoutData(gridData);
viewer.setContentProvider(new FileTreeContentProvider());
viewer.setLabelProvider(new FileTreeLabelProvider());
viewer.setInput(ResourcesPlugin.getWorkspace().getRoot().getProject(folderName.getText()));
viewer.expandAll();

Until here, everything is ok, but now, I don't know how to use listeners to do something when I select a specific item in my tree. Any idea? Thanks.

Edit: I got it!

    viewer.addSelectionChangedListener(
            new ISelectionChangedListener(){
                public void selectionChanged(SelectionChangedEvent event) {
                    if(event.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection)event.getSelection();            
                        Object o = selection.getFirstElement();    

                        if (o instanceof IFile){

                            IFile file = (IFile)o;

                        }else {
                            //what ?
                        }
                    }
                }
            }
    );

Upvotes: 0

Views: 111

Answers (1)

Yaza
Yaza

Reputation: 553

This is an excellent first step but there is even a better way which is more in the heart and soul of Eclipse.

Your code is listening to local changes but you want to make your code extendable so that other plugins in Eclipse are also notified when someone selects something in your viewer.

Eclipse 4 API

For this to happen you inject ESelectionService into your part and then forward the selection to the workbench by using the listener you already provided.

@Inject
private ESelectionService selectionService;

viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
  IStructuredSelection selection = (IStructuredSelection) event.getSelection();
  // set the selection to the service
  selectionService.setSelection(
      selection.size() == 1 ? selection.getFirstElement() : selection.toArray());

Then, to catch your own selection:

@Inject
void setSelection(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) IFile pFile) {
  if (pFile == null) {
    //what ?
  } else {
    // magic!
  }
}

Eclipse 3 API

For this to happen you have to register your viewer with the selection framework. Add this in the createPartControl method of the part where you have added your viewer:

    getSite().setSelectionProvider(viewer);

Then, to catch your own selection:

    getSite().getPage().addPostSelectionListener(this); // Implement ISelectionListener

References: https://wiki.eclipse.org/E4/EAS/Selection

Upvotes: 1

Related Questions