http://cs101.org/courses/fall05/psets/catandmouse/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;
public class View extends JPanel {
private World world;
public View(World world) {
this.world = world;
setPreferredSize(new Dimension(600,500));
}
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
Iterator it = world.getDisplayables();
while (it.hasNext()) {
Displayable item = (Displayable)it.next();
if (item instanceof Hidable) {
if (((Hidable)item).isHidden()) {
continue;
}
}
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);
g.translate(-bounds.x, -bounds.y);
g.setClip(oldClip);
}
}
}