Making the clouds look good - Images

Let us face it, drawing a line is too dry a thing to do; so let us move on to displaying an image on the screen. And to write an applet that displays an image is simpler than you ever feared. Consider this code...

import java.applet.*;
import java.awt.*;

public class zzz extends Applet { Image n; public void init() { n = getImage(getCodeBase(), "not.gif"); resize(300, 500); } public void paint(Graphics g) { g.drawImage(n, 10, 15, this); } }

As is amply apparent, the basic structure of the program remains the same. An object n that looks like the class Image is defined. Inside the init(), n is initialised to an image called "not.gif" which exists on our hard disk. (PS Check up the \demo\images directory for more .gif files which are nothing but images). This is done with the getImage() that is a member of the Applet class. As n looks like the class Image, it can use the member functions of that class. The getImage() accepts two parameters, the getCodeBase() and the name of the .gif file. Now, n contains the image "not.gif". So when the paint() is called using g (which looks like Graphics), we can use n to display the image. The Graphics class has a member function called drawImage(), which is used to actually draw the image (n) on to the screen. This takes four parameters. First is the image that we wish to draw, as is n in our case. The second and the third are the coordinates where we want the image to be displayed. The fourth parameter is this. If you are a C/C++ programmer, you are well-versed with this, but for the rest it should suffice right now to say that this refers to the current object ( pun unintended :-) ).

Now, the same image can be displayed at the coordinates where the user clicks by using the mouseUp() and trapping the coordinates where the mouse was clicked. If you have not got it already, the code for this will be..


import java.applet.*; import java.awt.* ;

public class zzz extends Applet { Image n; int a; int b;

public void init() { n = getImage(getCodeBase(), "not.gif"); resize(300, 500); } public void paint(Graphics g) { g.drawImage(n, a, b, this); } public boolean mouseUp(Event e, int x, int y) { a=x; b=y; repaint(); return true; } }

If your business partner has not run away with all your bank balance, pad up to the next chapter "Before we weave..."or spare a minute to tell us what you think about this tutorial.

Back to the Java page


Vijay Mukhi's Computer Institute
B-13, Everest Building, Tardeo, Bombay 400 034, India.
http://www.neca.com/~vmis
e-mail: vmukhi@giasbm01.vsnl.net.in