// file: testGraphics3.java // author: Robert Keller // purpose: Showing the fact that update repaints the background. // /* Notice the flicker when multiple images are drawn in this application This is because 'repaint' causes the system to call 'update' (not shown). Update a) redraws the background in the background color b) calls paint on the graphics it is given (the graphics of the frame) By un-commenting the commented-out code, we can make update repaint the background in the color we set. See testGraphics3a.java which has the code commented out. Notice the use of 'sleep' to achieve delay. This is preferable to a hard-wait loop, which uses valuable processor cycles. If the delay is too small or eliminated, it may be noticed that the image is sometimes displayed while it is being repainted, which is not aesthetically pleasing. */ import java.awt.*; // to get awt (abstract window toolkit) class testGraphics3 extends Frame // needed to allow over-ride of paint { // consider this to be magic for now Image image; // image provides graphics buffer // paint(Graphics) will be called by the system to paint the Frame when // necessary. At that time, the Graphics of the frame will be passed as // an argument. public void paint(Graphics g) { g.drawImage(image, 0, 0, null); } // draw stuff at position x, y void drawStuff(int x, int y) { Graphics g = image.getGraphics(); // get Graphics buffer g.setColor(Color.white); g.fillRect(0, 0, image.getWidth(null), image.getHeight(null)); g.setColor(Color.black); // set the color for drawing g.drawRect(x+50, y+50, 400, 300); // draw a rectangle g.setColor(Color.blue); g.fillOval(x+100, y+100, 300, 200); // fill an oval g.setColor(Color.yellow); g.drawOval(x+100, y+100, 300, 200); // draw an oval g.setFont(new Font("Times", Font.BOLD, 28)); g.setColor(Color.yellow); g.drawString("Harvey Mudd College", x+140, y+210); // draw a string } public static void main(String[] arg) { testGraphics3 frame = new testGraphics3(); // create the frame /* frame.setBackground(Color.white); // set the background color */ frame.reshape(50, 50, 600, 500); // set the location and size frame.show(); // show the frame // Note: the following must be done AFTER the frame is shown. frame.image = frame.createImage(frame.size().width, frame.size().height); for( int i = 0; i < 100; i += 10 ) { frame.drawStuff(i, i); try{Thread.sleep(5);} catch(Exception e){} // delay 5 milliseconds frame.repaint(); } } }