Thursday, October 28, 2010

Eclipse RCP: Images and Icons, Using ImageRegistry

Code examples are full of automagical ways of putting an image on a button or label. For example, your TreeViewer may set an ILabelProvider, which may have the following getImage method:

public Image getImage(Object obj) {
String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
}


But how do we add our own image to our plugin, and use it in a simple way?

Here's How:

In this example I've prepared two images and placed them in the project's icons directory:

In your plugin's Activator class override the initializeImageRegistry method.  For example:

@Override
protected void initializeImageRegistry(ImageRegistry registry) {
super.initializeImageRegistry(registry);
Bundle bundle = Platform.getBundle(PLUGIN_ID);

//
// Setup our own images to be used as icons, etc
//
ImageDescriptor image = ImageDescriptor.createFromURL(
FileLocator.find(bundle, new Path("icons/chart.gif"), null));

registry.put(ACTIVE_CHART, i);

image = ImageDescriptor.createFromURL(
FileLocator.find(bundle, new Path("icons/module.gif"), null));

registry.put(MODULE, i);

}


In the example code above, we prepare two images: module.gif and chart.gif .  Now we're ready to use them in a viewer's label. You should already know how to use a LabelProvider for your viewer. A LabelProvider is a class that implements ILabelProvider. In my case I had a TreeViewer that needed special icons on tree nodes.

My LabelProvider's getImage method:

@Override
public Image getImage(Object obj) {

// we'll just get the MODULE image
Image image = imageRegistry.get(gov.faa.ata.sdat.Activator.MODULE);

return image;

}



So there you have it.