Rotate a Java Graphics2D Rectangle?

For images you have to use drawImage method of Graphics2D with the relative AffineTransform.

For shape you can rotate Graphics2D itself:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.WHITE);
    Rectangle rect2 = new Rectangle(100, 100, 20, 20);

    g2d.rotate(Math.toRadians(45));
    g2d.draw(rect2);
    g2d.fill(rect2);
}

And btw, you should override paintComponent method instead of paint.

Citing JComponent's API:

Invoked by Swing to draw components. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing.

This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always. A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.

Remember also than when you perform an affine transformation, like a rotation, the object is implicitly rotated around the axis origin. So if your intent is to rotate it around an arbitrary point, you should before translating it back to the origin, rotate it, and then re-traslating it to the desired point.


public void draw(Graphics2D g) {
    Graphics2D gg = (Graphics2D) g.create();
    gg.rotate(angle, rect.x + rect.width/2, rect.y + rect.height/2);
    gg.drawRect(rect.x, rect.y, rect.width, rect.height);
    gg.dispose();

    gg = (Graphics2D) g.create();
    ... other stuff
}

Graphics.create() and Graphics.dispose() allow you to save the current transformation parameters (as well as current font, stroke, paint, etc), and to restore them later. It is the equivalent of glPushMatrix() and glPopMatrix() in OpenGL.

You can also apply an inverse rotation once you drew the rectangle to revert the transformation matrix back to its initial state. However, floating point approximations during substractions may lead to a false result.


Another way is by using Path2D, with it you can rotate the path only and not the entire graphics object:

Rectangle r = new Rectangle(x, y, width, height);
Path2D.Double path = new Path2D.Double();
path.append(r, false);

AffineTransform t = new AffineTransform();
t.rotate(angle);
path.transform(t);
g2.draw(path);