import java.awt.*;
import java.awt.event.*;

// A variation of a class that appears in Core Web
// Programming from Prentice Hall. May be freely used
// or adapted.
// 1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/

/** Draw "rubberband" rectangles when the user drags
 *  the mouse.
 */

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

  private int startX, startY, lastX, lastY;

  private class RectRecorder extends MouseAdapter {
    /** When the user presses the mouse, record the
     *  location of the top-left corner of rectangle.
     */
    public void mousePressed(MouseEvent event) {
      startX = event.getX();
      startY = event.getY();
      lastX = startX;
      lastY = startY;
    }

    /** Erase the last rectangle when the user releases
     *  the mouse.
     */
    public void mouseReleased(MouseEvent event) {
      Graphics g = getGraphics();
      g.setXORMode(Color.lightGray);
      g.drawRect(startX, startY,
                 lastX - startX, lastY - startY);
    }
  }

  private class RectDrawer extends MouseMotionAdapter {
    /** This draws a rubberband rectangle, assuming
     *  you first choose the top-left corner, then draw
     *  down and to the right.
     */
    public void mouseDragged(MouseEvent event) {
      int x = event.getX();
      int y = event.getY();
      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;
    }
  }

  public Rubberband() {
    super("Click and drag to show rubberbanding");
    addMouseListener(new RectRecorder());
    addMouseMotionListener(new RectDrawer());
    setBackground(Color.white);
    setSize(500, 300);
    setVisible(true);
  }
}

