Java Reference
In-Depth Information
You can also calculate this distance without creating the points by using the static method:
double lineLength = Point2D.distance(2.5, 3.5, 20, 30);
Corresponding to each of the three
distance()
methods is a convenience method,
distanceSq()
,
with the same parameter list that returns the square of the distance between two points as a value of
type
double
.
3. Comparing points:
The
equals()
method compares the current point with the point object refer-
enced by the argument and returns
true
if they are equal and
false
otherwise.
4. Setting a new location for a point:
The
setLocation()
method comes in two versions. One ac-
cepts an argument that is a reference of type
Point2D
and sets the coordinate values of the current point
to those of the point passed as an argument. The other accepts arguments of type
double
that are the
x
and
y
coordinates of the new location. The
Point
class also defines a version of
setLocation()
that
accepts two arguments of type
int
to define the new coordinates.
Lines and Rectangles
The
java.awt.geom
package contains the following classes for shapes that are straight lines and rectangles:
•
Line2D
: This is an abstract base class defining a line between two points. Two concrete subclasses
—
Line2D.Float
and
Line2D.Double
— define lines in terms of user coordinates of type
float
and
double
, respectively. You can see from their names that the subclasses are nested classes to
the abstract base class
Line2D
.
•
Rectangle2D
: This is the abstract base class for the
Rectangle2D.Double
and
Rect-
angle2D.Float
classes that define rectangles. A rectangle is defined by the coordinates of the
position of its top-left corner plus its width and height. The
Rectangle2D
class is also the abstract
base class for the
Rectangle
class in the
java.awt
package, which stores the position coordinates
and the height and width as values of type
int
.
•
RoundRectangle2D
: This is the abstract base class for the
RoundRectangle2D.Double
and
RoundRectangle2D.Float
classes, which define rectangles with rounded corners. The rounded
corners are specified by a width and height.
Like the
java.awt.Point
class, the
java.awt.Rectangle
class predates the
Rectangle2D
class, but the
definition of the
Rectangle
class was changed to make
Rectangle2D
a base for compatibility reasons. Note
that there is no equivalent to the
Rectangle
class for lines defined by integer coordinates. If you are brows-
ing the documentation, you might notice there is a
Line
interface, but this declares operations for an audio
channel and has nothing to do with geometry.
Figure 19-7
illustrates how, lines, rectangles, and round rectangles are defined.