import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
* Holds part of the Model data
*/
public class Square { //*4 Unit test code goes here
/** Classvar to generate unique positions for each instance */
static private int squareCount = 0;
/** Enumerated type for which action to take on a square */
public enum ButtonAction {LEFT, RIGHT, BIGGER, SMALLER};
private Canvas canvas;
/** Info about the square */
private Rectangle loc;
/**
* Standalone unit test for Square class.
* Not called in normal usage,
* run it separately with "java Square"
*/
public static void main (String[] args) { //*4
// Need a dummy object here for testing
Canvas canvas = new Canvas ();
ArrayList<Square> squares = new ArrayList<Square> (); //*1 Create some squares
for (int i=0; i<10; i++) { //*1
squares.add (new Square(canvas)); //*1
}
for (Square s: squares) { //*2 Print them out
System.out.println ("Square at " + s.loc); //*2
if (s.isInside (new Point (50, 50))) { //*2
System.out.println ("50,50 is inside"); //*2
}
}
squares.get(0).doAction (ButtonAction.BIGGER); //*3 Test some actions, print again
squares.get(1).doAction (ButtonAction.RIGHT); //*3
squares.get(2).doAction (ButtonAction.LEFT); //*3
squares.get(2).doAction (ButtonAction.SMALLER); //*3
System.out.println ("");
for (Square s: squares) { //*3
System.out.println ("Square at " + s.loc); //*3
if (s.isInside (new Point (50, 50))) { //*3
System.out.println ("50,50 is inside"); //*3
}
}
}
public Square (Canvas canvas) {
this.canvas = canvas;
// Keep count
squareCount++;
// Initial values
loc = new Rectangle (30*squareCount, 10*squareCount, 50, 50);
}
public void draw (Graphics g, boolean isCurrent) {
Graphics2D g2 = (Graphics2D) g;
if (isCurrent)g2.fill (loc);
else g2.draw (loc);
}
public boolean isInside (Point p) {
return loc.contains (p);
}
public void doAction (ButtonAction action) {
if (action==ButtonAction.LEFT) loc.x -= 10;
else if (action==ButtonAction.RIGHT) loc.x += 10;
else if (action==ButtonAction.BIGGER) { loc.width += 10; loc.height += 10; }
else if (action==ButtonAction.SMALLER) { loc.width -= 10; loc.height -= 10; }
canvas.repaint();
}
}