Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SWT: Working with images

SWT provides Image class to draw images. Following step-by-step procedure explains sample application to draw images.

Step 1: Define an image instance and add it to the display.
String imagePath = "C:\\java.png";
Image img = new Image(display, imagePath);

Step 2: Use drawImage method of Graphic context instance.

GC gc = new GC(shell);
gc.drawImage(img, 200, 200);

Step 3: Dispose image and graphic context.
img.dispose();
gc.dispose();

Following is the complete working application.
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {

private static int shellWidth = 500;
private static int shellHeight = 500;

private static String imagePath = "java.png";

private static void addGraphicsToShell(Display display, Shell shell) {
Image img = new Image(display, imagePath);
shell.open();
GC gc = new GC(shell);
gc.drawImage(img, 200, 200);
img.dispose();
gc.dispose();

}

public static void main(String[] args) {

/* Instantiate Display object, it represents SWT session */
Display display = new Display();

/*
* Define Shell, it represent a window, You can add more than one shell
* to Display
*/
Shell shell = new Shell(display);
shell.setSize(shellWidth, shellHeight);
shell.setText("SWT Tutorial");

addGraphicsToShell(display, shell);

/*
* Run the event dispatching loop until an exit condition occurs, which
* is typically when the main shell window is closed by the user.
*/

while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}

/* Dispose the display */
display.dispose();

}
}

Run above application, you can able to see following window.




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

SWT: Working with images

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×