Monday, 17 June 2013

How to show up an image with swt in java?


The simplest way to create an SWT Image is to load it from a recognized graphic file format. This includes GIF, BMP (Windows format bitmap), JPG, and PNG. The TIFF format is also supported in more recent Eclipse releases.
Images can be loaded from a known location in the file system using the constructor
Image(Display display, String fileLocation):
Eg:
Image image = new Image(display,
   "C:/eclipse/eclipse/plugins/org.eclipse.platform_2.0.2/eclipse_lg.gif");
Instead of hard-coding the location of the image, it's more common to load the Image from a folder location relative to a given class. This is done by creating an InputStream pointing to the file with the method
Class.getResourceAsStream(String name),
and using the result as the argument to the constructor
 Image(Display display, InputStream inputStream).
Eg: If in Eclipse package explorer the class com.foo.ShellWithButtonShowingEclipseLogo and the eclipse_lg.gif in the same folder.
To load the graphic from its location relative to the class.
Image image = new Image(display, 
    ShellWithButtonShowingEclipseLogo.class.getResourceAsStream(
      "eclipse_lg.gif"));
Then you can add it on your label as:
Label myLabel = new Label( shell, SWT.NONE );
myLabel.setImage( image );

No comments:

Post a Comment