// file: testGraphics4.java // author: Robert Keller // purpose: Showing how to redefine update. // /* In this program, we over-ride the 'update' method of the base Frame. This is the standard model for flicker-free graphics in the JDK 1.0 AWT. By over-riding update, we can have it not draw the background at all. Then we call paint and have it draw the off-screen image, which has its own background. Compare with testGraphics3a, where there can be some flicker. Here there is no flicker. The image motion is a bit jerky because the step size is fairly large (10 pixels). We could make the step size smaller, but then the image would not appear to move as fast. */ import java.awt.*; // to get awt (abstract window toolkit) import java.lang.Thread; class testGraphics4 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); } public void update(Graphics g) { paint(g); } // draw stuff at position x, y void drawStuff(int x, int y) { Graphics g= image.getGraphics(); g.setColor(Color.white); // paint image background 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.drawString("Harvey Mudd College", x+140, y+210); // draw a string } public static void main(String[] arg) { testGraphics4 frame = new testGraphics4(); // create the frame 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(); } } }