Java Reference
In-Depth Information
double x2 = in.readDouble();
double y2 = in.readDouble();
line = new Line2D.Double(0,0,x2,y2);
}
That's lines serialized. Looks as though it's going to be easy. We can do rectangles next.
Serializing Rectangles
A rectangle is always drawn with its top left corner at the origin, so we only need to write the width and
height to the file:
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeDouble(rectangle.width);
out.writeDouble(rectangle.height);
}
The width and height members of the Rectangle2D.Double object are public , so we can access
them directly to write them to the stream.
Deserializing an Element.Rectangle object is almost identical to the way we desirialized a line:
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
double width = in.readDouble();
double height = in.readDouble();
rectangle = new Rectangle2D.Double(0,0,width,height);
}
An Element.Circle object is actually going to be easier.
Serializing Circles
A circle is drawn as an ellipse with the top left corner of the bounding rectangle at the origin. The only
item of data we will need to reconstruct a circle is the diameter:
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeDouble(circle.width);
}
The diameter is recorded in the width member (and also in the height member) of the
Ellipse2D.Double object. We just write it to the file.
We can read a circle back with the following code:
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
double width = in.readDouble();
circle = new Ellipse2D.Double(0,0,width,width);
}
This reconstitutes the circle using the diameter that was written to the file.
Search WWH ::




Custom Search