/** * GeomShapeDriver.java * Driver for the GeomShape class and its subclasses. * * @author Scot Drysdale on 4/9/00. Modified to use JApplet. * Minor changes by THC. */ import java.awt.*; import javax.swing.*; public class GeomShapeDriver extends JApplet { private static final long serialVersionUID = 1L; /** * Initializes the applet */ public void init() { setBackground(Color.white); setSize(500, 500); Container cp = getContentPane(); // Content pane holds components cp.add(new Canvas()); // The canvas is the only component setVisible(true); // Makes the applet (and its components) visible } /** * Serves as the drawing canvas for graphics. */ private class Canvas extends JPanel { private static final long serialVersionUID = 1L; /** * Paints this component. * @param page the Graphics object that we draw on. */ public void paintComponent(Graphics page) { super.paintComponent(page); GeomShape shape = null; // reference to an object that can be a Circle, Rect, or Segment for (int i = 1; i <= 3; i++) { if (i == 1) { shape = new Circle(300, 200, 75, Color.magenta); page.drawString("circle has area " + shape.areaOf(), 15, 20); shape.draw(page); ((Circle) shape).scale(0.5); // note we must cast shape } else if (i == 2) { shape = new Rect(150, 200, 50, 25, Color.red); page.drawString("rectangle has area " + shape.areaOf(), 15, 40); } else if (i == 3) { shape = new Segment(20, 150, 100, 160, Color.blue); page.drawString("segment has area " + shape.areaOf(), 15, 60); } // Notice the polymorphism: the first time through the loop, // shape references a Circle, the second time it references a Rect, // and the third time it references a Segment. With dynamic binding, // the appropriate draw and move methods are called each time. shape.draw(page); shape.move(-5, -35); shape.draw(page); } } } }