I'm stuck again on a problem concerning SWT using Java RCP.
I have a Composite in which I wanna load an Image in it.
For this, I use a SWT Label, and call the method setImage(image). The image (img.jpg) is found in a directory called /img/ next to the /src/ one. The directory is added in the Build Path. Here's a screen to illustrate : directories
I call this image as follows :
InputStream is = getClass().getClassLoader().getResourceAsStream("/img/img.jpg");
ImageData imageData = new ImageData(is);
Label label = new Label(picRoom, SWT.NONE);
label.setImage(new Image(display, imageData));
Once again, when I launch the project, everything goes right. The image loads and displays perfectly. But when I export it, the image doesn't anymore. The problem comes from the path actually. When I make an image as new Image(display, absolutePathToTheImage)
, it loads even if exported. But I want the image in the /img/ directory, because if I launch the project from the .exe from another computer, I want it to have the picture, wherever it is (so in /img/).
I've tried many solutions across the internet (using URL in particular), but no one worked. And as I said, I need the image to be in the /img/ directory and to take the relative path. And, of course, to work after exporting the project as a .exe .
Kosnyru.
First make sure your img
directory is included in the build.properties
includes so that it is included in the exported plugin.
Then use the FileLocator
class to find the image using a relative path:
// Your plugin's bundle - there are several ways to get this
Bundle bundle = FrameworkUtil.getBundle(getClass());
// Relative path in the plugin
String path = "/img/img.jpg";
URL url = FileLocator.find(bundle, new Path(path), null);
ImageDescriptor imageDesc = ImageDescriptor.createFromURL(url);
Image image = imageDesc.createImage();