Option 1: Redraw everything in paint

1. Idea

Have user actions change non-graphical data structures, then call repaint. The paint method will completely redraw each of the data structures.

2. Example DrawCircles.java: (Download Source)

import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

public class DrawCircles extends CloseableFrame {
  public static void main(String[] args) {
    new DrawCircles();
  }

  private Vector circles;

  /** When you click the mouse, create a SimpleCircle,
   *  put it in the Vector, and tell the system
   *  to repaint (which calls update, which clears
   *  the screen and calls paint).
   */

  private class CircleDrawer extends MouseAdapter {
    public void mousePressed(MouseEvent event) {
      circles.addElement(new SimpleCircle(event.getX(),
                                          event.getY(),
                                          25));
      repaint();
    }
  }

  public DrawCircles() {
    super("Drawing Circles");
    circles = new Vector();
    addMouseListener(new CircleDrawer());
    setBackground(Color.white);
    setSize(500, 300);
    setVisible(true);
  }

  /** This loops down the available SimpleCircle
   *  objects, drawing each one.
   */
  public void paint(Graphics g) {
    SimpleCircle circle;
    for(int i=0; i<circles.size(); i++) {
      circle = (SimpleCircle)circles.elementAt(i);
      circle.draw(g);
    }
  }
}

3. SimpleCircle.java: (Download Source)

import java.awt.*;

/** A class to store an x, y, and radius, plus a
 *  draw method.
 */

public class SimpleCircle {
  private int x, y, radius;

  public SimpleCircle(int x, int y, int radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  /** Given a Graphics, draw the SimpleCircle
   *  centered around its current position.
   */
  public void draw(Graphics g) {
    g.fillOval(x - radius, y - radius,
               radius * 2, radius * 2);
  }

  public int getX() { return(x); }
  public void setX(int x) { this.x = x; }

  public int getY() { return(y); }
  public void setY(int y) { this.y = y; }

  public int getRadius() { return(radius); }
  public void setRadius(int radius) {
    this.radius = radius;
  }
}

4. DrawCircles Output

© 1996-99 Marty Hall, 1999 Lawrence M. Brown