简体   繁体   中英

Java Swing moving java.awt.Shape

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 :

  1. Find a trick to move a java.awt.Shape Seems to be the best solution but I can't figure how to do that.

  2. 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.

But there is no translate or move methods on java.awt.Shape s.

See AffineTransform.createTransformedShape(Shape) , which:

Returns a new Shape object defined by the geometry of the specified Shape 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. ..

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

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM