Java Reference
In-Depth Information
The following statement produces the union of the two rectangles:
Rectangle2D.Float rect3 = rect1.createUnion(rect2);
The result is shown in
Figure 19-8
by the rectangle with the heavy boundary that encloses the other two.
Testing Rectangles
Perhaps the simplest test you can apply to a
Rectangle2D
object is for an empty rectangle. The
isEmpty()
method that is implemented in all the rectangle classes returns
true
if the
Rectangle2D
object is empty —
which is when either the width or the height (or both) are zero.
You can also test whether a point lies inside any type of rectangle object by calling its
contains()
meth-
od. There are
contains()
methods for all the rectangle classes that accept either a
Point2D
argument, or
a pair of (
x,y
) coordinates of a type matching that of the rectangle class: They return
true
if the point lies
within the rectangle and
false
otherwise. Every shape class defines a
getBounds2D()
method that returns
a
Rectangle2D
object that encloses the shape.
The
getBounds2D()
method is frequently used in association with the
contains()
method to provide
an efficient test of whether the cursor lies within a particular shape. Testing whether the cursor is within
the enclosing rectangle is a lot faster in general than testing whether it is within the precise boundary of the
shape and is good enough for many purposes — for example, when you are selecting a particular shape on
the screen to manipulate it in some way.
You also have versions of the
contains()
method to test whether a given rectangle lies within the area
occupied by a rectangle object — this obviously enables you to test whether a shape lies within another
shape. You can pass the given rectangle to the
contains()
method as the coordinates of its top-left corner,
and its height and width as type
double
, or as a
Rectangle2D
reference. The method returns
true
if the
rectangle object completely contains the given rectangle.
Let's try drawing a few simple lines and rectangles by inserting some code in the
paint()
method for
the view in Sketcher.
TRY IT OUT: Drawing Lines and Rectangles
Begin by adding an
import
statement to
SketcherView.java
for the class names from the
java.awt.geom
package: