import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; /** * The "model" (vs. user interface) part of this program */ public class Model { /** Model or application data */ private ArrayList<Square> squares = new ArrayList<Square> (); private boolean drawX = false; private Canvas canvas; private Square current; //*3 Private = no other class can cause the bug public Model (int n, Canvas canvas) { // Stash ivar this.canvas = canvas; // Create the n objects for (int i=0; i<n; i++) { squares.add (new Square(canvas)); } // Initialize to some arbitrary square so current is never null Square current = squares.get(0); //*1 Initialize current // assert => we expect this always to be true assert current != null; //*2 Should always be true } public void draw (Graphics g) { // The background X if (drawX) { Dimension size = canvas.getSize(); g.drawLine (0, 0, size.width, size.height); g.drawLine (0, size.height, size.width, 0); } // Enumerate our list for (Square s: squares) { // N.B. (s==current) is a boolean expr, // evaluates to true or false s.draw (g, s==current); } assert current != null; //*2 } public void setX (boolean newX) { drawX = newX; canvas.repaint(); assert current != null; //*2 } Square getCurrent () { //*4 We provided read-only access to current assert current != null; //*2 return current; //*4 } public void doMouse (Point p) { for (Square s: squares) { if (s.isInside(p)) { current = s; break; } } canvas.repaint(); assert current != null; //*2 } }