Java Reference
In-Depth Information
Directory "TryPolyLine"
How It Works
The
PolyLine
class has the data members
start
and
end
that you saw in
Figure 6-7
.
These reference the
first and last points of the list, or
null
if the list is empty. Storing the end point in the list is not essential
because you can always find it by going through the list starting with
start
. However, having a referen-
ce to the last point saves a lot of time when you want to add a point to the list. The constructor accepts
an array of
Point
objects and uses the
addPoint()
method to add all the points in the array to the list.
Adding a point to the list is deceptively simple. All the
addPoint()
method does is create a
ListPoint
object from the
Point
object passed as an argument, sets the
next
member of the old end point in the list
to refer to the new point, and finally stores a reference to the new end point in the member
end
.
The
toString()
method returns a string representing the
PolyLine
object as a list of point coordinates.
Note how the
next
member of the
ListPoint
objects controls the loop that runs through the list. When
the last
ListPoint
object is reached, the
next
member will be returned as
null
and the
while
loop ends.
You can now give the
PolyLine
class a whirl.
TRY IT OUT: Using PolyLine Objects
You can create a simple example to illustrate the use of the
PolyLine
class:
public class TryPolyLine {
public static void main(String[] args) {
// Create an array of coordinate pairs
double[][] coords = { {1, 1}, {1, 2}, { 2, 3},
{-3, 5}, {-5, 1}, {0, 0} };
// Create a polyline from the coordinates and display it
PolyLine polygon = new PolyLine(coords);
System.out.println(polygon);
// Add a point and display the polyline again
polygon.addPoint(10, 10);
System.out.println(polygon);
// Create Point objects from the coordinate array
Point[] points = new Point[coords.length];
for(int i = 0; i < points.length; ++i)
points[i] = new Point(coords[i][0],coords[i][1]);
// Use the points to create a new polyline and display it
PolyLine newPoly = new PolyLine(points);
System.out.println(newPoly);
}