// file: testGraphics2.java // author: Robert Keller // purpose: Showing how to off-screen buffer the graphics. // This will ultimately allow animation without flicker. /* Explanation: In testGraphics1.java, we put the drawing commands for various items directly in the 'paint' method for the frame. In this program, we instead draw the items into a different graphics context, one which is part of an Image object used for an off-screen buffer. When we paint, we paint the entire image, which contains all the items that were drawn in it. Thus we do not have to wait while the items are being drawn, just while the image is being painted, which generally requires less computation time. You can may the difference when the window is uncovered, or un-iconified, which also causes the 'paint' method to be called. In testGraphics1, you will may see the letters being re-drawn by the paint method. In this program, you won't see the letters being re-drawn, because they are already drawn in the Image. The paint method is instead drawing the image, which is generally faster and smoother. */ import java.awt.*; // to get awt (abstract window toolkit) class testGraphics2 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); } void drawStuff() { Graphics g = image.getGraphics(); // get Graphics buffer g.setColor(Color.black); // set the color for drawing g.drawRect(50, 50, 400, 300); // draw a rectangle g.setColor(Color.blue); g.fillOval(100, 100, 300, 200); // fill an oval g.setFont(new Font("Times", Font.BOLD, 28)); g.setColor(Color.yellow); g.drawString("Harvey Mudd College", 140, 210); // draw a string } public static void main(String[] arg) { testGraphics2 frame = new testGraphics2(); // create the frame frame.setBackground(Color.white); // set the background color frame.reshape(50, 50, 500, 400); // set the location and size frame.show(); // show the frame // Note: the following must be done AFTER the frame is shown. // as size() does not get set until then. frame.image = frame.createImage(frame.size().width, frame.size().height); frame.drawStuff(); } }