Computer Science 120
Introduction to Programming

Spring 2012, Siena College

Rectangles Demo

A working demo of Rectangles will appear below. Click inside the applet to interact with it.



Rectangles BlueJ Project

Click here to download a BlueJ project for Rectangles.


Rectangles Source Code

The Java source code for Rectangles is below. Click on a file name to download it.


Rectangles.java

import objectdraw.*;

/*
 * This program draws rectangles interactively.  When the mouse is
 * pressed, the coordinates are saved as one corner of a rectangle to
 * be drawn.  As the mouse is dragged, a rectangle is drawn with that
 * point as one corner, the current point as the other.  Finally, when the
 * mouse is relased, the final rectangle is drawn.
 *
 * Jim Teresco, Siena College, CSCI 120, Spring 2011
 *
 * $Id: Rectangles.java 1496 2011-01-20 20:01:52Z terescoj $
 */
public class Rectangles extends WindowController {

  // Coordinate of one corner of the rectangles being drawn
  private Location firstCorner;
  // last temporary rectangle drawn during a drag
  private FramedRect tempRect;

  /*
   * When the mouse is pressed, save the press point to be used as
   * the first corner of a rectangle to draw
   */
  public void onMousePress(Location point) {
    firstCorner = point;
    tempRect = null;
  } 

  /*
   * As the user is dragging, remove any temp rectangle already drawn,
   * draw a rectangle from the saved point to current point.
   */
  public void onMouseDrag(Location point) {

    if (tempRect != null) tempRect.removeFromCanvas();
    tempRect = new FramedRect(firstCorner, point, canvas);
  }

  /*
   * Done dragging, remove any temp rectangle already drawn,
   * draw a rectangle from the saved point to current point.
   */
  public void onMouseRelease(Location point) {

    if (tempRect != null) tempRect.removeFromCanvas();
    new FramedRect(firstCorner, point, canvas);
  }
}