import java.awt.*;

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

/** Draw "rubberband" rectangles when the user drags
 *  the mouse. Ignore problems with dragging into
 *  or out of the window.
 */

public class Rubberband extends QuittableFrame {
  public static void main(String[] args) {
    new Rubberband();
  }
  
  private int startX, startY, lastX, lastY;
  
  public Rubberband() {
    super("Click and drag to show rubberbanding");
    setBackground(Color.white);
    resize(500, 300);
    show();
  }

  /** When the user presses the mouse, record the
   *  location of the top-left corner of rectangle.
   */
  public boolean mouseDown(Event e, int x, int y) {
    startX = x;
    startY = y;
    lastX = startX;
    lastY = startY;
    return(true);
  }

  /** This draws a rubberband rectangle, assuming
   *  you first choose the top-left corner, then draw
   *  down and to the right.
   */
  public boolean mouseDrag(Event e, int x, int y) {
    Graphics g = getGraphics();
    g.setXORMode(Color.lightGray);
    g.drawRect(startX, startY,
               lastX - startX, lastY - startY);
    g.drawRect(startX, startY,
               x - startX, y - startY);
    lastX = x;
    lastY = y;
    return(true);
  }

  /** Erase the last rectangle when the user releases
   *  the mouse.
   */
  
  public boolean mouseUp(Event e, int x, int y) {
    Graphics g = getGraphics();
    g.setXORMode(Color.lightGray);
    g.drawRect(startX, startY,
               lastX - startX, lastY - startY);
    return(true);
  }
}

