Java Reference
In-Depth Information
A starting point is to figure out the extent of the sketch. Ideally you 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
java.awt.Rectangle
object enclosing the element. As you saw in Chapter 17, the
Rectangle
class defines an
add()
method that combines the
Rectangle
object that you pass as the argument with the
Rectangle
object for which you called the method, and returns the smallest
Rectangle
object that encloses
both; this is referred to as the
union
of the two rectangles. With these two bits of information and by ac-
cessing the elements in the list in the
SketcherModel
object, you can get a rectangle that encloses the entire
sketch by implementing the following method in the
SketcherModel
class:
// Get the rectangle enclosing an entire sketch
Rectangle getModelExtent() {
Rectangle rect = new Rectangle();
// An empty rectangle
for(Element element : elements) {
// Go through the list
rect.add(element.getBounds());
// Expand union
}
if(rect.width == 0) {
// Make sure width
rect.width = 2;
// is non-zero
}
if(rect.height == 0) {
// and the height
rect.height = 2;
}
return rect;
}
Directory "Sketcher 7 printing the whole sketch"
Don't forget to add an
import
statement for the
Rectangle
class name to the
SketcherModel
source
file:
import java.awt.Rectangle;
Using the collection-based
for
loop to iterate over the elements in the list, you generate the union of
the bounding rectangles for all the elements, so you end up with a rectangle that bounds everything in the
sketch. A zero width or height for the rectangle is unlikely, but you want to be sure it can't happen because
you use these values as divisors later. A minimum width and height of 2 ensures that the rectangle has an
interior.
the rectangle that encloses all the bounding rectangles for the individual elements. If you visualize the origin
of the user coordinate system being placed at the top-left corner of the printable area on the page, you can
appreciate that a section of the sketch in the illustration is hanging out to the left outside the printable area.
This can arise quite easily in Sketcher — when you are drawing a circle with the center close to either of the
axes, for example, or if you move a shape so this is the case. You can avoid missing part of the sketch from
the printed output by first translating the origin of the graphics context to the top-left corner of the printable
area on the page and then translating the origin of the coordinate system to the top-left corner of
rect
.