Monday, February 11, 2008

How to retrieve an image for an action or button

There are several way to achieve this:

1) many common images (undo, redo, file, folder, cut, copy) are available through the org.eclipse.ui.ISharedImages interface:

Image folderImg = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);

2) If you have your own image in the plugin path, with the help of AbstractUIPlugin:

ImageDescriptor imageDescriptorFromPlugin = AbstractUIPlugin.imageDescriptorFromPlugin(MyFunnyPlugin.PLUGIN_ID, "icons/stop.gif");

The good thing is that the path is relative to the plugin containing it (in this case MyFunnyPlugin) and is URL-alike, i.e. slash on every operating system.
Sometimes all you need is the descriptor, as in the case of actions:

Action stopGpsAction = new Action(){
public void run() {
// stop that thing

sometimes you need the image instead, as in the case of icons for buttons:

Button stop = new Button(commandGroup, SWT.PUSH | SWT.BORDER);

3) If however your resource lies in the same package of the calling class, you can exploit:

ImageData imageData = new ImageData(getClass().getResourceAsStream("legenda_pioggia.png"));
Image image = new Image(display, imageData);

No comments: