Java Draw Images Graphics

Java Draw Images Graphics

Java Draw Images Graphics

Summary: Java permits to draw images in graphics. Explained in this tutorial "Java Draw Images Graphics" in simple terms, code and screenshot. Go through.

To draw images, the Graphics class includes a method drawImage(). Drawing images requires special coding using ImageObserver.

2. Drawing Images in Applications (Frames)

After seeing how to draw images on applets, let us see how to draw on frames. Both come with different code. getImage() method works in applets as getImage() is a method of Applet class. To work with frames, getImage() method also exist with Toolkit class. Following program illustrates.

Java Draw Images Graphics
Output screen of of Java Draw Images Graphics

Toolkit tkit = Toolkit.getDefaultToolkit();
Image img = tkit.getImage("bird4.gif");

getDefaultToolkit() is a static method of abstract class, java.awt.Toolkit. This method returns an object of Toolkit. Any image to be drawn is to be converted into an object of image. getImage() method of Toolkit class returns an object of Image class, here it is, img. img object represents bird4.gif as an object of Image class.

g.drawImage(img, 60, 80, this);

Graphics is an abstract class from java.awt package and contains many methods of drawing. One of such methods is drawImage() that takes four parameters. The first parameter is the image to be drawn as an object of Image class. The second and third parameters are x and y coordinates where the image is to be drawn on the frame window. The last parameter is an object of ImageObserver. The "this" argument in the above statement refers an object of ImageObserver.

Now, where from the JVM gets the reference of ImageObserver? The super class of Applet, java.awt.Component class implements the ImageObserver (observe, the hierarchy of Applet in Applets topic). From its super class, Applet gets the reference of ImageObserver.

Observe how drawImage() method is defined in Graphics class.

boolean drawImage(Image img, int x, int y, ImageObserver observer);

To practice drawing of image in an applet refer Drawing Images of Multimedia.

Programming Tip: java.awt.Image is an abstract class. Do not try to create an object. Get the Image object by calling getImage() method Toolkit class. getImage() method creates and returns an Image object in specific format known to the underlying OS.

Leave a Reply

Your email address will not be published. Required fields are marked *