Reputation: 2347
We have an application that displays a kind of map. This Swing application mainly draw a set of java.awt.Shape
s with java.awt.Graphics2D#draw(Shape)
and everything is fine.
And now, I have to extend this app to allow our users editing (moving shapes on) the map. But there is no translate
or move
methods on java.awt.Shape
s. So I can't change the position (java.awt.Point
) of a shape.
I have tried to override java.awt.Shape#getPathIterator
in order to apply a translation that matches the shape position. But It's tricky because this method already accept a transformation that I have to merge and also because to be correct the PathIterator
should then start at (0, 0)
because it is relative to the shape position.
And anyway, that won't work because it seems that Graphics2D
don't always use this method to draw a java.awt.Shape
.
So now, I'm feeling a bit lost. Another solution could be to let shapes drawn themselves, but then I have to rewrite a part of the application. That's not a problem but I have to know which could be the best solution :
Find a trick to move a java.awt.Shape
Seems to be the best solution but I can't figure how to do that.
Change the app to have self drawing shapes
Could be nice but then I have to compute myslef the contains
and other more complex methods.
Upvotes: 1
Views: 3962
Reputation: 2347
@AndrewThompson's solution seems to be the best one. And I'm going to give it a try.
For those interested (Because I had to progress). I have created one interface who extends java.awt.Shape
and has a setter for his location property.
Each specific shape has to implement the code needed to update his location but it is much easier than having to move any kind of shape.
Upvotes: 0
Reputation: 168845
But there is no
translate
ormove
methods onjava.awt.Shape
s.
See AffineTransform.createTransformedShape(Shape)
, which:
Returns a new
Shape
object defined by the geometry of the specifiedShape
after it has been transformed by this transform.
Of course, there is also Graphics2D.translate(x,y)
..
Translates the origin of the
Graphics2D
context to the point (x, y) in the current coordinate system. ..
Upvotes: 7
Reputation: 57421
You can create Area based on your Shape and call transform() passing AffineTransform with translated coordinates.
Area a=new Area(sourceShape);
AffineTransform at=new AffineTransform();
at.translate(horizontalShift, verticalShift);
Shape transformedShape=a.transform(at);
Haven't tested though
Upvotes: 4