Java 2d rotation in direction mouse point

Using the Graphics2D rotation method is indeed the easiest way. Here’s a simple implementation:

int centerX = width / 2;
int centerY = height / 2;
double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2;

((Graphics2D)g).rotate(angle, centerX, centerY);

g.fillRect(...); // draw your rectangle

If you want to remove the rotation when you’re done so you can continue drawing normally, use:

Graphics2D g2d = (Graphics2D)g;
AffineTransform transform = g2d.getTransform();

g2d.rotate(angle, centerX, centerY);

g2d.fillRect(...); // draw your rectangle

g2d.setTransform(transform);

It’s a good idea to just use Graphics2D anyway for anti-aliasing, etc.

Leave a Comment