Java Reference
In-Depth Information
Element element; // Stores an element
while(elements.hasNext()) { // Go through the list
element = (Element)elements.next(); // Get the next element
g2D.setPaint(element.getColor()); // Set the element color
g2D.draw(element.getShape()); // Draw its shape
}
}
// Method called by Observable object when it changes
public void update(Observable o, Object rectangle) {
// Code to respond to changes in the model...
}
private Sketcher theApp; // The application object
}
The
getModel()
method that we implemented in the
Sketcher
class returns a reference to the
SketchModel
object, and this is used to call the
getIterator()
method which will return an iterator
for the list of elements. Using a standard
while
loop, we iterate through all the elements in the list. For
each element, we obtain its color and pass that to the
setPaint()
method for the graphics context.
We then pass the
Shape
reference returned by the
getShape()
method to the
draw()
method for
g2D
. This will draw the shape in the color passed previously to the
setPaint()
method. In this way
we can draw all the elements stored in the model.
It's time we put in place the mechanism for creating Sketcher shapes.
Drawing Using the Mouse
We've drawn shapes so far using data internal to the program. In our Sketcher program we want to be
able to draw a shape using the mouse in the view, and then store the finished shape in the model. We
want the process to be as natural as possible, so we'll implement a mechanism that allows you to draw
by pressing the left mouse button (more accurately, button 1) and dragging the cursor to draw the
selected type of shape. So for a line, the point where you depress the mouse button will be the start
point for the line, and the point where you release the button will be the end point.