Pretty elegant way to provide images in eclipse UI plug-ins
Donnerstag, 8. Juli, 2010 – 17:55Loading images is an ever-recurring task in Eclipse plug-in development. So I figured out a pretty elegant solution to provide images and image descriptors within my UI plug-ins.
The pro’s about it are:
- Image paths are used and defined at exactly one place within the plug-in.
- You have a constant for all of your images
- Images are handled and disposed by the plug-ins’ registry.
- Images and image descriptors are registered and created lazyly on demand.
- Only pre-defined images can be used.
- Wrong image paths result in an image proxy, this solution never returns a null value.
And the best thing about it is the elegant syntax to get an image or an image descriptor:
Image image = UIImages.FIRST_ICON.getImage(); ImageDescriptor imageDescriptor = UIImages.FIRST_ICON.getImageDescriptor();
So this is how it works:
package de.wendehals.ui.plugin; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; /** * This enumeration provides a number of images for the plugin. */ public enum UIImages { FIRST_ICON("icons/first.gif"), SECOND_ICON("icons/second.gif"); // add more image enumerations here... private final String path; private UIImages(final String path) { this.path = path; } /** * Returns an image. Clients do not need to dispose the image, it will be disposed automatically. * * @return an {@link Image} */ public Image getImage() { final ImageRegistry imageRegistry = UIPlugin.getDefault().getImageRegistry(); Image image = imageRegistry.get(this.path); if (image == null) { addImageDescriptor(); image = imageRegistry.get(this.path); } return image; } /** * Returns an image descriptor. * * @return an {@link ImageDescriptor} */ public ImageDescriptor getImageDescriptor() { final ImageRegistry imageRegistry = UIPlugin.getDefault().getImageRegistry(); ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(this.path); if (imageDescriptor == null) { addImageDescriptor(); imageDescriptor = imageRegistry.getDescriptor(this.path); } return imageDescriptor; } private void addImageDescriptor() { final UIPlugin plugin = UIPlugin.getDefault(); final ImageDescriptor id = ImageDescriptor.createFromURL(plugin.getBundle().getEntry(this.path)); plugin.getImageRegistry().put(this.path, id); } }
Of course what you need is a plug-in class (here UIPlugin) extending AbstractUIPlugin to provide the image registry. More images can be added by adding a new enumeration value with the image’s path.
Hope, you like it too. Feel free to use it in your UI plug-ins.
