Java Reference
In-Depth Information
if(removed) {
setChanged();
notifyObservers(element.getBounds());
}
return removed;
}
//Add an element to the sketch
public void add(Element element) {
elements.add(element);
setChanged();
notifyObservers(element.getBounds());
}
// Get iterator for sketch elements
public Iterator<Element> iterator() {
return elements.iterator();
}
protected LinkedList<Element> elements = new LinkedList< >();
private final static long serialVersionUID = 1001L;
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
All three methods make use of methods that are defined for the
LinkedList<Element>
object,
elements
,
so they are very simple. When you add or remove an element, the model is changed, so you call the
setChanged()
method inherited from
Observable
to record the change and the
notifyObservers()
meth-
od to communicate this to any observers that have been registered with the model. The observers are the
views that display the sketch. You pass the
java.awt.Rectangle
object that is returned by
getBounds()
for the element to
notifyObservers()
. Each of the shape classes defined in the
java.awt.geom
package
implements the
getBounds()
method to return the rectangle that bounds the shape. You are 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 example — so you test the
boolean
value that is returned by the
remove()
method for the
LinkedList<Element>
object. You also return this value from the
remove()
method in the
SketcherModel
class, as the caller may want to know if an element was removed or not.
The
iterator()
method returns an iterator of type
Iterator<Element>
for the linked list that holds the
elements in the sketch. This can be used to iterate over all the elements in a sketch. It also allows an element
to be removed using the
remove()
method that is declared in the
Iterator<>
interface.
Even though you haven't defined any of the element classes that Sketcher supports, you can still make
provision for displaying them in the view class.
Drawing Shapes
You draw the shapes in the
paint()
method for the
SketcherView
class, so if you haven't already done
so, remove the old code from the
paint()
method now. You can replace it with code for drawing Sketcher
shapes like this: