Java Reference
In-Depth Information
iterator.next(); // Go to next segment
}
out.writeObject(coords); // Save the Vector
}
We obtain a java.awt.geom.PathIterator object for the Element.Curve object that we will use
to extract the segment data for the curve. We will have to import this class into Element.java . We
create a Vector object in which we will store the coordinate data as objects and we will serialize this
vector in the serialization of the curve. We also create a float[] array to hold the numerical
coordinate values for a segment. All six elements are used when the segment is a cubic Bezier curve. In
our case fewer are used but we must still supply an array with six elements as an argument to the
currentSegment() method because that's what the method expects to receive.
After verifying that the first segment is a move-to segment, we use the path iterator to extract the
segment data that defines the curve. We use the Float class constructor to create Float objects to
store in the Vector object coords . The assertion is there to make sure that the curve consists only of
line segments after the initial move-to.
We will need an import statement for Vector to make the class accessible in the Element.java
source file:
import java.util.Vector;
It's worth considering how we might handle a GeneralPath object that consisted of a variety of
different segments in arbitrary sequence. For the case where the path consisted of a set of line, quad, or
cubic segments, you could get away with using a Vector object to store the coordinates for each
segment, and then store these objects in another Vector . You could deduce the type of segment from
the number of coordinates you have stored in each Vector object for a segment since line, cubic, and
quad segments each require a difference number of points. In the general case you would need to define
classes to represent the segments of various types, plus moves, of course. If these had a common base
class, then you could store all the objects for a path in a Vector as base class references. Of course, you
would need to make sure your segment classes were serializable too.
To deserialize a curve, we just have to read the Vector object from the file, and recreate the
GeneralPath object for the Element.Curve class:
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
Vector coords = (Vector)in.readObject(); // Read the coordinates Vector
curve = new GeneralPath(); // Create a path
curve.moveTo(0,0); // Move to the origin
float x, y; // Stores coordinates
for(int i = 0 ; i<coords.size() ; i += 2 ) { // For each pair of elements
x = ((Float)coords.get(i)).floatValue(); // Get x value
y = ((Float)coords.get(i+1)).floatValue(); // Get y value
curve.lineTo(x,y); // Create a line segment
}
}
Search WWH ::




Custom Search