// // another example of the Java AWT, showing creation of an Image // an image. // see class definition for details. // // this example is modified from a similar example in chapter 17 of // _Exploring Java_ (Niemeyer and Peck). // import java.awt.* ; import java.awt.event.* ; import java.awt.image.* ; // // a ColorPan object is a DrawingFrame that displays an image generated // from an array of integers representing RGB color values. the // colors vary across and down the image. if the window is // resized, the image is scaled to fit. // class ColorPan extends DrawingFrame implements ComponentListener { private Image img ; private int imgWidth, imgHeight ; private int pixelData[] ; ColorPan(Dimension dims) { super("ColorPan") ; setDrawingSize(dims) ; initializeImage(dims) ; addComponentListener(this) ; show() ; } // initializes image -- set img to null (so paint() will // recreate), set width and height, create pixel data. private void initializeImage(Dimension dims) { img = null ; imgWidth = dims.width ; imgHeight = dims.height ; pixelData = new int [imgWidth * imgHeight] ; int i=0 ; for (int row = 0 ; row < imgHeight ; row++) { int red = (row * 255) / (imgHeight - 1) ; for (int col = 0 ; col < imgWidth ; col++) { int green = (col * 255) / (imgWidth - 1) ; int blue = 128 ; int alpha = 255 ; pixelData[i++] = (alpha << 24) | (red << 16) | (green << 8) | (blue) ; } } } // creates onscreen image from pixel data. public void paint(Graphics g) { System.out.println("paint called") ; if (img == null) { System.out.println("creating new image") ; img = createImage( new MemoryImageSource( imgWidth, imgHeight, pixelData, 0, imgWidth)) ; } // position origin to avoid frame borders. translateDrawingArea(g) ; // draw image. g.drawImage(img, 0, 0, this) ; } // updates onscreen image (no need to clear first, just paint). public void update(Graphics g) { System.out.println("update called") ; paint(g) ; } // called when component is resized. public void componentResized(ComponentEvent e) { System.out.println("componentResized called") ; initializeImage(getDrawingSize()) ; repaint() ; } // other methods of ComponentListener interface. public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } // // ---- main --------------------------------------------------- // // command-line arguments: initial width, height // (defaults 400, 200) // public static void main(String[] args) { int w = 400 ; int h = 200 ; if (args.length >= 2) { w = Integer.parseInt(args[0]) ; h = Integer.parseInt(args[1]) ; } ColorPan c = new ColorPan(new Dimension(w, h)) ; } }