I want to get notified when an editor is opened in Eclipse. What is the best way to do that?
From this thread
Have your class implement org.eclipse.ui.IPartListener2.
Then you get notified when a workbench part (anIEditorPart
, etc.) just got opened/closed. You can actually filter out which parts you want to pay attention to.
(note: As of 3.5, the IPartListener2 can also implement IPageChangedListener
to be notified about any parts that implement IPageChangeProvider
and post PageChangedEvents
.)
The tricky part (no pun intended) is to register the listener to workbench.
So, the first thing to do is get a valid
IWorkbenchPage
so that you can callIWorkbenchPage.addPartListener(
.)
Here is how to get a workbench page.
IWorkbenchPage page = null;
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null)
{
page = window.getActivePage();
}
if (page == null)
{
// Look for a window and get the page off it!
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (int i = 0; i < windows.length; i++)
{
if (windows[i] != null)
{
window = windows[i];
page = windows[i].getActivePage();
if (page != null)
break;
}
}
}
See also here.
See this class as an example
IPartListener2 partlistener = new IPartListener2(){
public void partActivated( IWorkbenchPartReference partRef ) {
if (partRef.getPart(false) == MapEditor.this){
registerFeatureFlasher();
ApplicationGIS.getToolManager().setCurrentEditor(editor);
}
}
[...]
Or this generic PartListener for generic usage of a PartListener2.
Or this EditorTracker