Eclipse RCP - how to listen for selection from the editor in focus
I have created a simple Eclipse RCP application where I can open multiple editor instances based on user action. I have a separate view (ViewPart) where I listen for the selection changes on the editor. The problem is that the view is notified only of the selections from the last opened editor, the other editors which were opened earlier don't provide the events any more/or maybe the view listens only to the last opened editor and nothing else. This happens even if the previously opened editors gain focus.
In other words, only the newest editor in editor area provides selection events, what I want is, when I click on the other editor's tabs, I want to see the changes on my view when I click one of the previously opened editors.
In my view I use:
IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getActiveWorkbenchWindow().getActivePage().addSelectionListener(DocumentsEditor.ID,(ISelectionListener)this);
开发者_如何学Pythonwhere DocumentEditor is one of the editors opened in application editor area.
From the JavaDoc for ISelectionService.addSelectionListener(String partId, ISelectionListener listener)
(emphasis is mine):
Adds a part-specific selection listener which is notified when selection changes in the part with the given id. This is independent of part activation - the part need not be active for notification to be sent.
When the part is created, the listener is passed the part's initial selection. When the part is disposed, the listener is passed a null selection, but only if the listener implements INullSelectionListener.
Note: This will not correctly track editor parts as each editor does not have a unique partId.
So don't use this method when you want to track editor selections. Instead use ISelectionService.addSelectionListener(ISelectionListener listener)
and check the given part in ISelectionListener.selectionChanged(IWorkbenchPart part, ISelection selection)
using instanceof
...
Small note to the code: The selection service exists on a per window basis, so if you have multiple workbench windows, they each have their own service instance.
For this reason I usually use the following code in my views and editors:
ISelectionService ss = getSite().getWorkbenchWindow().getSelectionService();
ss.addPostSelectionListener(listener);
This way the used listener will come from the correct window.
精彩评论