import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; /** * Holds part of the Model data */ public class Square { /** 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) { // Need a dummy object here for testing Canvas canvas = new Canvas (); ArrayList squares = new ArrayList (); for (int i=0; i<10; i++) { squares.add (new Square(canvas)); } for (Square s: squares) { System.out.println ("Square at " + s.loc); if (s.isInside (new Point (50, 50))) { System.out.println ("50,50 is inside"); } } squares.get(0).doAction (ButtonAction.BIGGER); squares.get(1).doAction (ButtonAction.RIGHT); squares.get(2).doAction (ButtonAction.LEFT); squares.get(2).doAction (ButtonAction.SMALLER); System.out.println (""); for (Square s: squares) { System.out.println ("Square at " + s.loc); if (s.isInside (new Point (50, 50))) { System.out.println ("50,50 is inside"); } } } 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(); } }