http://cs101.org/courses/fall05/psets/catandmouse/View.java
/*
 * View.java
 */

package catandmouse;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.util.Iterator;
import javax.swing.JPanel;

/**
 * A view of all of the Displayable objects in the model.
 */
public class View extends JPanel {
    private World world;
    
    /** Creates a new instance of View */
    public View(World world) {
        this.world = world;
        setPreferredSize(new Dimension(600,500));
    }
    
    public void paint(Graphics g) {
        // erase everything first
        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());
        // draw all of the displayables
        Iterator it = world.getDisplayables();
        while (it.hasNext()) {
            Displayable item = (Displayable)it.next();
            if (item instanceof Hidable) {
                // don"t draw any Hidables that are hidden.
                if (((Hidable)item).isHidden()) {
                    continue;
                }
            }
            // shift the origin and set the clip so that each Displayable
            // feels like it"s drawing at the origin, no matter where it
            // really is.
            Rectangle bounds = item.getBounds();
            Shape oldClip = g.getClip();
            g.clipRect(bounds.x, bounds.y, bounds.width, bounds.height);
            g.translate(bounds.x, bounds.y);
            item.paint(g);
            // restore the old origin and clip
            g.translate(-bounds.x, -bounds.y);
            g.setClip(oldClip);
        }
    }
    
}