Programmatically Fire a RCP Selection Event

uı6ʎɹnɯ ꞁəıuɐp picture uı6ʎɹnɯ ꞁəıuɐp · Feb 1, 2012 · Viewed 18.5k times · Source

In my Eclipse RCP application I use the Selection Service as described in this nice article. There is a TreeViewer in one view registered as a SelectionProvider:

getSite().setSelectionProvider(viewer);

Another view is receiving the events from the TreeViewer:

selectionListener = new ISelectionListener() {
  public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    pageSelectionChanged(part, selection);
  }
 };
 getSite().getPage().addSelectionListener(selectionListener);

Everything works fine, if the events are triggered my normal mouse clicks. I would like to programmatically fire a selection events by selection an item in the tree:

treeViewer.setSelection(new StructuredSelection(element),true);

This is not working. Method selectionChanged is not called in the receiver-view. The issue is discussed in this forum thread. There is no solution.

EDIT

There is no proper way to handle a mouse triggered click the same way as a programmatically selection. A mouse click activates the view a programmatically selection does not.

My Solution is to register the second view the same way by Selection Service as the first view. After that both view are getting selection events directly from the active editor.

Answer

user847988 picture user847988 · Sep 13, 2012

You can do two things:

1) do the selection and then call notify listeners for an SWT.SELECTION i.e. :

mybutton.setSelection(true);
mybutton.notifyListeners(SWT.Selection, new Event());

The notifyListener method is intented to be used for custom controls so to be more correct you could do option number 2.

2) call the method that you call in your listener i.e.:

this.myButton.addSelectionListener(new SelectionListener() {
    public void widgetSelected(final SelectionEvent e) {
      doSomethingaboutTheSelMethod();
 }

In this case you can call:

doSomethingaboutTheSelMethod();