import java.awt.*; import java.util.*; public class Region { // Default width and height (in pixels) of a square. private final int SQUARE_SIZE = 20; public static boolean DEBUGGING = false; /** * EFFECT: Initialize a region with the given position, dimensions, * and color. */ public Region (int upperLeftX, int upperLeftY, int width, int height, Color c) { myUpperLeftX = upperLeftX; myUpperLeftY = upperLeftY; myWidth = width; myHeight = height; myColor = c; myId = ourNextId; ourNextId++; mySquares = new SquareList ( ); } /** * EFFECT: Return true if this region contains the point at * coordinates (x,y). */ public boolean contains (int x, int y) { boolean result = x >= myUpperLeftX && x <= myUpperLeftX+myWidth && y >= myUpperLeftY && y <= myUpperLeftY+myHeight; if (DEBUGGING) { System.out.print ("Region " + myId); if (result) { System.out.println (" contains (" + x + "," + y + ")"); } else { System.out.println (" does not contain (" + x + "," + y + ")"); } } return result; } /** * REQUIRES: This region contains the point (x,y). * MODIFIES: this. * EFFECTS: Determine which of this region's squares cover the pixel * coordinate (x,y). If there are any, remove them. If there were * none, add a square centered at (x,y) to this region's squares, * making sure it doesn't extend outside the region. */ public void handleClick (int x, int y) { if (!mySquares.handleClick (x, y)) { int leftDistance = min (SQUARE_SIZE/2, x-myUpperLeftX); int rightDistance = min (SQUARE_SIZE/2, myUpperLeftX+myWidth-x); int upDistance = min (SQUARE_SIZE/2, y-myUpperLeftY); int downDistance = min (SQUARE_SIZE/2, myUpperLeftY+myHeight-y); int xDistance = min (leftDistance, rightDistance); int yDistance = min (upDistance, downDistance); int size = 2 * min (xDistance, yDistance); mySquares.add (new Square (x, y, size, myColor)); } } /** * REQUIRES: g != null. * MODIFIES: the displayed window. * EFFECT: Draws the region by first drawing a white-filled rectangle, * then drawing the border, then telling all the squares in the region * to draw (paint) themselves. */ public void paint (Graphics g) { g.setColor (Color.white); g.fillRect (myUpperLeftX, myUpperLeftY, myWidth, myHeight); g.setColor (Color.black); g.drawRect (myUpperLeftX, myUpperLeftY, myWidth, myHeight); Iterator iter = mySquares.elements ( ); while (iter.hasNext ( )) { Square sq = (Square) iter.next ( ); sq.paint (g); } } /** * REQUIRES: o != null; o's type is a subclass of Region. * EFFECT: Returns true when this region has the same position * and dimensions as o. */ public boolean equals (Object o) { Region r = (Region) o; return myUpperLeftX == r.myUpperLeftX && myUpperLeftY == r.myUpperLeftY && myWidth == r.myWidth && myHeight == r.myHeight; } /** * EFFECT: Returns the larger of a and b. */ public static int max (int a, int b) { return a>b? a: b; } /** * EFFECT: Returns the smaller of a and b. */ public static int min (int a, int b) { return a