# Java Graphics2D not rotating right

## Recommended Posts

Hello,

I tried to make a program where two rectangles are rotating around their centers.

But the second of them is orbiting around the first one.

Code:

private void drawRect(int x, int y, int width, int height, double angle,
Graphics2D g2) {
AffineTransform old = g2.getTransform();
AffineTransform af = new AffineTransform();
(double) height / 2.0);

g2.transform(af);

g2.fillRect(x, y, width, height);

g2.transform(old);
}


and then:

g2.setColor(Color.BLUE);
drawRect(0,0,100,100,angle,g2);

g2.setColor(Color.RED);
drawRect(200,200,50,100,angle2,g2);
angle+=0.3;
angle2++;


I tried using g2.rotate first,but it gave me the same problem,so I tried using AffineTransform.Of course,nothing changed...

Screenshot is attached.

Help!!!

Thanks,

MatejaS

##### Share on other sites

This looks like homework.

It looks like you're using the transform() method which takes the given transform and adds it to the current transform, but you want the setTransform() method which overwrites the current transform with the new transform.

http://docs.oracle.com/javase/8/docs/api/java/awt/Graphics2D.html#transform-java.awt.geom.AffineTransform-

##### Share on other sites

Thanks @Glass_Knife but it didn't help...

It seems that even if I remove all code for drawing the blue rect,the red rect still orbites.Same thing if I first draw red,and then blue rect... Weird...

And it's not homework :)

##### Share on other sites

and you changed it all to setTransform() and it still didn't work?  Hmm.  It is time to create a condensed example and post to whole thing so someone can run it or at least see everything.

I do remember that the AffineTransform does a column major multiply, so the combinations go in reverse order from what you might expect, but I've done this before and it does work just like it should.

##### Share on other sites

Maybe I'm wrong here, but the anchor point you are using for your rotation is just width/2, height/2, you have to adjust for the x and y coordinates of the rectangle. If you modify your anchor point to:

af.rotate(Math.toRadians(angle), (double) (x + width / 2.0),
(double) (y + height / 2.0));

Let us know...

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627748
• Total Posts
2978911

• 10
• 10
• 21
• 14
• 14