/* a simple program to create and display a raster image.  Can be run as either
   an applet or an application - written by Matt Ward */

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;

public class RasterTest extends Applet {

    RasterCanvas canvas;  // a canvas with an image in it
    static final int width = 400; // constant dimensions for canvas and frame
    static final int height = 400;

    public void init() {
// make a canvas of stated size
	setLayout(new BorderLayout());
	add("Center", canvas = new RasterCanvas());
        canvas.setSize(width,height);
// create a buffer to hold pixel values and fill with random grey values
        int pixels[] = new int[width * height];
        int index = 0;
        int alpha = 255;
        int red, green, blue;
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                red = i%255; // (int) (Math.random() * 256.);
                green = j%255; //red;
                blue = 0; //red;
                pixels[index++] = (alpha << 24) | (red << 16) | (red << 8) |
                    red;
                }
            }
// create an image to hold pixel array
	Image img = createImage(new MemoryImageSource(width, height,
	    ColorModel.getRGBdefault(), pixels, 0, width));
// put the image on the canvas
        canvas.setImage(img, width, height);
        }  // end init()

//  the entry point for the application - just create a frame and insert applet
    public static void main(String args[]) {
	RasterFrame f = new RasterFrame("RasterTest");
        f.setSize(width, height);
	f.show();
        }  // end main()
    }  // end RasterTest class

// extend Frame class to allow graceful window closing (copied from 
// Graphic Java book)
class RasterFrame extends Frame {
    public RasterFrame(String frameTitle)  {
        super(frameTitle);
        RasterTest app = new RasterTest();
        app.init();
        app.start();
        add(app, "Center");
        addWindowListener(new WindowAdapter()   {
           public void windowClosing(WindowEvent event) {
              dispose();
              System.exit(0);
              }
              });
        }
    }  // end RasterFrame class

// extend Canvas class to include a raster image and its dimensions
class RasterCanvas extends Canvas {
    Image img;
    int width;
    int height;

// the paint method simply draws the raster
    public void paint(Graphics g) {
        g.drawImage(this.img, 0, 0, this.width, this.height, this);
        }

// set the raster
    public void setImage(Image img, int w, int h)  {
        this.img = img;
        this.width = w;
        this.height = h;
        }
    }  // end RasterCanvas class
