Java Reference
In-Depth Information
The boulder on the left only appears in part. I know it's not all on the screen, but it's all in the model, so
I was hoping to see the picture in its full glory. If you think about it, it's very optimistic to believe that
we could automatically get the whole sketch printed. First of all, neither the PrinterJob object nor
the view object has any idea how big the sketch is. That's a fairly fundamental piece of data if you want
a complete sketch printed. Another consideration is that the left extremity of the boulder on the left of
the sketch is to the left of the y axis, but I'd rather like to see it in the picture. It would be nice if we
could take account of that too. Let's see how we might do it.
Note that material change to the Element subclasses will cause problems. Sketches serialized
before the changes will not deserialize after.
Printing the Whole Sketch
A starting point is to figure out the extent of the sketch. Ideally we need a rectangle that encloses all the
elements in the sketch. It's really surprisingly easy to get that. Every element has a getBounds()
method that returns a Rectangle object enclosing the element. As we saw in Chapter 15, the
Rectangle class also defines a member add() method. It combines a Rectangle object passed as an
argument with the Rectangle object for which it is called, and returns the smallest Rectangle object
that will enclose both: this is referred to as the union of the two rectangles. With these two bits of
information and an iterator from element list in the SketchModel object, we can get the rectangle
enclosing the entire sketch by implementing the following method in the SketchModel class:
// Get the rectangle enclosing an entire sketch
Rectangle getModelExtent() {
Iterator elements = getIterator();
Rectangle rect = new Rectangle(); // An empty rectangle
Element element; // Stores an element
while(elements.hasNext()) { // Go through the list
element = (Element)elements.next(); // Get the next element
rect.add(element.getBounds()); // Expand union
}
if(rect.width == 0) // Make sure width
rect.width = 1; // is non-zero
if(rect.height == 0) // and the height
rect.height = 1;
return rect;
}
Don't forget to add an import for the Rectangle class to the SketchModel source file:
import java.awt.Rectangle;
Using the iterator for the element list, we expand the bounding rectangle for every element so we end
up with a rectangle that bounds everything in the sketch. A zero width or height for the rectangle is
unlikely, but we want to be sure it can't happen because we will use these values as divisors later.
Search WWH ::




Custom Search