// file: MyApplet3.java // author: Robert M. Keller // purpose: Demonstrate use of off-screen buffer // Prints trace messages import java.applet.*; import java.awt.*; public class MyApplet3 extends Applet { Image buffer; // Image to be drawn on screen by paint method Graphics graphics; // Graphics part of image, acts as buffer // Initialize the applet. public void init() { System.out.println("*** init() called"); buffer = createImage(size().width, size().height); graphics = buffer.getGraphics(); } // Called to start the applet after init. public void start() { System.out.println("*** start() called"); drawStuff(graphics); repaint(); } // repaint over-ride is just for purposes of tracing public void repaint() { System.out.println("*** repaint() called"); super.repaint(); } // update is implicitly called when repaint() is called // g will be bound to the Graphics object in the Applet, // not the one in the buffer. paint will draw the buffer into g. public void update(Graphics g) { System.out.println("*** update() called"); paint(g); } // draw items in Graphics void drawStuff(Graphics g) { System.out.println("*** drawStuff() called"); // dimensions and offsets int xCenter = 250; int yCenter = 200; int rectWidth = 400; int rectHeight = 300; int ovalWidth = 300; int ovalHeight = 200; String hmc = "Harvey Mudd College"; g.setFont(new Font("Times", Font.BOLD, 20)); int stringOffset = xCenter - g.getFontMetrics().stringWidth(hmc)/2; int stringBase = 10 + yCenter; // background color g.setColor(Color.white); g.fillRect(0, 0, size().width, size().height); // shapes g.setColor(Color.black); g.drawRect(xCenter-rectWidth/2, yCenter-rectHeight/2, rectWidth, rectHeight); g.fillOval(xCenter-ovalWidth/2, yCenter-ovalHeight/2, ovalWidth, ovalHeight); // lettering g.setColor(Color.yellow); g.drawString("Harvey Mudd College", stringOffset, stringBase); } // paint(Graphics) is called by update(g) and whenever // the screen needs painting (such as when it is newly exposed) public void paint(Graphics g) { System.out.println("*** paint() called"); g.drawImage(buffer, 0, 0, null); } }