Java Reference
In-Depth Information
notifyObservers(element.getBounds());
}
public Iterator getIterator() {
return elementList.listIterator();
}
protected LinkedList elementList = new LinkedList();
}
All three methods make use of methods defined in the LinkedList class so they are very simple. The
add() and remove() functions have a parameter type of Element so only our shapes can be added to
the linked list or removed from it. When we add or remove an element, the model is changed and
therefore we call the setChanged() method inherited from Observable to record the change, and
the notifyObservers() method to communicate this to any observers that have been registered with
the model. We pass the Rectangle object returned by getBounds() for the shape to
notifyObservers() . Each of the shape classes defined in java.awt.geom implements the
getBounds() method to return the rectangle that bounds the shape. We will be able to use this in the
view to specify the area that needs to be redrawn.
In the remove() method, it is possible that the element was not removed - because it was not there for
instance - so we test the boolean value returned by the remove() method for the LinkedList
object. We also return this value, as the caller may want to know if an element was removed or not.
Next, even though we haven't defined any of our specific shape classes, we can still make provision for
displaying them in the view class.
Drawing Shapes
We will draw the shapes in the paint() method for the SketchView class, so remove the old code
from the paint() m ethod now. We can replace it for drawing our own shapes like this:
import javax.swing.JComponent;
import java.util.*;
import java.awt.*;
class SketchView extends JComponent implements Observer {
public SketchView(Sketcher theApp) {
this.theApp = theApp;
}
// Method called by Observable object when it changes
public void update(Observable o, Object rectangle) {
// Code to respond to changes in the model...
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g; // Get a 2D device context
Iterator elements = theApp.getModel().getIterator();
Search WWH ::




Custom Search