ButtonApp4: Model.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*; //*1 Use ArrayList

/**
 * The "model" (vs. user interface) part of this program
 */
public class Model {
    /** Model or application data */
    private ArrayList<Square> squares = new ArrayList<Square> (); //*1
    private boolean drawX = false; //*3 Handle drawing background X

    private Canvas canvas;
    private Square current; //*2 We tell Square if it's current or not

    public Model (int n, Canvas canvas) {
	// Stash ivar
	this.canvas = canvas;

	// Create the n objects
	for (int i=0; i<n; i++) { //*1
	    squares.add (new Square(canvas)); //*1
	}

	// Initialize to some arbitrary square so current is never null
	current = squares.get(0); //*1
    }

    public void draw (Graphics g) { //*3
	// The background X
	if (drawX) { //*3
	    Dimension size = canvas.getSize(); //*3
	    g.drawLine (0, 0, size.width, size.height); //*3
	    g.drawLine (0, size.height, size.width, 0); //*3
	}

	// Enumerate our list
	for (Square s: squares) { //*1
	    // N.B. (s==current) is a boolean expr,
	    // evaluates to true or false
	    s.draw (g, s==current); //*2
	}
    }

    public void setX (boolean newX) { //*3
	drawX = newX; //*3
	canvas.repaint(); //*3
    }

    Square getCurrent () {
	return current;
    }

    public void doMouse (Point p) { //*2
	for (Square s: squares) { //*2
	    if (s.isInside(p)) { //*2
		current = s; //*2
		break; //*2
	    }
	}
	
	canvas.repaint();
    }
}

[download file]