Making Bricks

Brick Applet: Obviously you could make this little applet using calls to fillRect without any need to create images, but the point of this demonstration applet if for you to see how to create an image and set the pixels in that image. So, you will need to study the explanations provided down on the page in order to create this applet.

There are a few things you need to be aware of inorder to successfully complete this applet:

First Item: You need to do a special import for java.awt.image.*

import.awt.image.*;


Second Item: You need to declare two instances of the Image class before the init method:

Image red_brick, yellow_brick;


Third Item: You need to define your two instances of the image class in the init method:

red_brick=makeBrick(20,10,1);
yellow_brick=makeBrick(20,10,2);


Fourth Item: You need to create a method which defines all the pixels for your bricks:

public Image makeBrick(int w, int h, int color){ int pixels[] = new int[w*h]; for(int i = 0; i<w*h; i++){ if(color==1) pixels[i]=Color.red.getRGB(); else pixels[i]=Color.yellow.getRGB(); } return createImage(new MemoryImageSource(w,h,pixels,0,w)); } }

EXPLANATION: You should first notice that the pixels array is used in the call to MemoryImageSource. Before this call you populate the pixels array with integer values which represent color values. The integer values for colors can be returned using the getRGB() method in the java.awt.Color class. This makes it easy to determine the integer value for a particular color.

Fifth Item: You need to call the drawImage method in your paint method. The drawImage takes four arguments. The first is the image to be drawn. The next two designate the upper-left corner of the image in the applet area. The last one has to be an instance of the ImageObserver class. An applet qualifies as an ImageObserver.

public void paint(Graphics g){ g.drawImage(red_brick, 10, 10, this); g.drawImage(yellow_brick, 60, 10, this); }