java/swing: Shape questions: serializing and combining
I have two questions about java.awt.Shape
. Suppose I have two Shape
s, shape1
and shape2
.
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 notSerializable
开发者_开发百科 but it does have thegetPathIterator()
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 aShape
object afterwards.)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)
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 Shape
s, 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. Shape
s are generally constructed transiently.
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.
精彩评论