Java Reference
In-Depth Information
package name to distinguish it from the inner class type
Rectangle
. The constructor is
protected
because
it is only called by inner class constructors.
The return type for the
getBounds()
method that makes the bounding rectangle for an element available
is fully qualified by the package name. This is to avoid confusion with your own
Rectangle
class that you
add as an inner class later in this chapter.
There are two
abstract
methods that must be implemented by the subclasses. This means that the
Ele-
ment
class must be declared as
abstract
. An implementation of the
draw()
method draws an element using
the
Graphics2D
object that is passed to it. The
modify()
method alters the definition of an element using
the
Point
objects that are passed to it as defining points.
Storing Shapes in the Model
Even though you haven't defined the classes for the shapes that Sketcher creates, you can implement the
mechanism for storing them in the
SketcherModel
class. You'll store all of them as objects of type
Ele-
ment
, so you can use a
LinkedList<Element>
collection class object to hold an arbitrary number of
Ele-
ment
objects. The container for
Element
references needs to allow deletion as well as additions to the con-
tents, and you will want to remove items and rearrange the order of items, too. This makes a linked list the
best choice. A map container just doesn't apply to Sketcher data. An
ArrayList<>
or a
Vector<>
contain-
er doesn't really fit the bill. Neither is it very efficient when you want to remove items on a regular basis
whereas deleting a shape from a linked list is fast.
You can add a member to the
SketcherModel
class that you defined earlier in the Sketcher program to
store elements:
import java.io.Serializable;
import java.util.*;
public class SketcherModel extends Observable implements Serializable {
// Detail of the rest of class to be filled in later...
protected LinkedList<Element> elements = new LinkedList<>();
private final static long serialVersionUID = 1001L;
}
You definitely want methods to add and delete
Element
objects. It is also very useful if the
Sketcher-
Model
class implements the
Iterable<Element>
interface because that allows a collection-based
for
loop
to be used to iterate over the
Element
objects stored in the model. Here's how the class looks to accommod-
ate that:
import java.io.Serializable;
import java.util.*;
public class SketcherModel extends Observable
implements Serializable, Iterable<Element> {
//Remove an element from the sketch
public boolean remove(Element element) {
boolean removed = elements.remove(element);