views:

28

answers:

2

I have two questions about java.awt.Shape. Suppose I have two Shapes, shape1 and shape2.

  1. How can I serialize them in some way so I can save the information to a file and later recreate it on another computer? (Shape is not Serializable but it does have the getPathIterator() method which seems like you could get the information out but it would be kind of a drag + I'm not sure how to reconstruct a Shape object afterwards.)

  2. How can I combine them into a new Shape so that they form a joint boundary? (e.g. if shape1 is a large square and shape2 is a small circle inside the square, I want the combined shape to be a large square with a small circular hole)

+2  A: 

I believe you can reconstruct a Shape from path information with java.awt.geom.Path2D.Double. However, it may not be as efficient as specific implementations.

To be serialisable without special work from all classes that have a Shape as a field, then you would need to ensure that all constructed shapes serialisable subclasses of the provided Shapes, that initialise data in a readObject method. If there are cases where you need to send data to the constructor, then you will need "serial proxies" (I don't think this is necessary in this case).

It might well be better to serialise the underlying model data. Shapes are generally constructed transiently.

Tom Hawtin - tackline
But how will such a path behave when the input one contains splines or Bezier curves ? Won't it be interpolated and loose its vectorial abilities ?
Riduidel
@Riduidel I think `getPathIterator(AffineTransform)` returns those segments, but `getPathIterator(AffineTransform,double)` does not. I guess in general a `Shape` may return an approximate path.
Tom Hawtin - tackline
A: 

I think I figured out an answer to the 2nd part of my question:

Shape shape1, shape2;
shape1 = ...;
shape2 = ...;
Area area = new Area(shape1);
area.subtract(new Area(shape2));
// "area" is now a Shape that is the difference between the two shapes.
Jason S