Eclipse : Change Editor Icon

if you want to set default icon for files opened in your Editor, you can do so when associating editor with file types in plugin.xml as below:

//MyEditor.plugin.xml
< extension point="org.eclipse.ui.editors" >
< editor
class="com.smaple.MyEditor"
contributorClass="com.sample.MyEditor.ActionContributor"
default="true" extensions="txt"
icon="icons/myTxtIcon.gif"
id="com.sample.MyEditor.txt"
name="%editor.txt.label">
< / editor >
< / extension >


Now if you want to change this icon at runtime (e.g. you may want to show different icon for files outside workspace), you can do so in your editor class as below:


public class MyEditor extends TextEditor{

private static final Map IMAGE_DESCRIPTOR_MAP = new HashMap();
public static final Image IMAGE_EXTERNAL_ICON;
static{
IMAGE_EXTERNAL_ICON = getImageDescriptor("icons/myIcon.gif").createImage();
}
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
IResource res = (IResource) getEditorInput().getAdapter(IResource.class);
if(res == null){
//set the icon for external files
Image image = getExternalImage();
if(image != null){
// call the setTitleImage defined in WorkbenchPath
setTitleImage(image);
}
}
}

private Image getExternalImage() {
IPath path = new Path(getEditorInput().getName());

if (isTxtFile(path)){
return IMAGE_EXTERNAL_ICON;
}
return null;
}

public static ImageDescriptor getImageDescriptor(String name) {
if (IMAGE_DESCRIPTOR_MAP.containsKey(name)) {
return (ImageDescriptor)IMAGE_DESCRIPTOR_MAP.get(name);
} else {
try {
URL url = MyEditorPlugin.getDefault().getBundle().getEntry(name);
ImageDescriptor d = ImageDescriptor.createFromURL(url);
IMAGE_DESCRIPTOR_MAP.put(name, d);
return d;
} catch (Exception e) { // should not happen
return ImageDescriptor.getMissingImageDescriptor();
}
}
}
}