Rotating Rectangle about its Centre
Hi all,
I'm trying to get to grips with drawing graphics in Java at the moment so I've decided to try and draw a rectangle on the screen and allow the user to move and rotate it using keyboard keys.
I've been able to do most of it, but now I'm stuck on the rotation of the rectangle in that it doesn't rotate correctly as it rotates about a point in the screen (where the rectangle is initially drawn) and not its central point. It's a bit difficult to explain in text but if you imagine a rectangle being created at the centre of a clock face and then moved to the edge (at say 3) when you try and rotate the rectangle it pivots on the centre of the clock face and not its own centre.
Basically, I want to always rotate the rectangle about its centre point only. I understand that using the translate and rotate methods actually moves the whole co-ordinate system not just the rectangle so I guess my question is how after rotating and translating can I restore the coordinate system back to as it was before I did anything (translate, rotate)?
Here is my code:
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.*;
public class ShapeExample extends JPanel implements KeyListener {
int x;
int y;
double rotation;
public ShapeExample() {
setFocusable(true);
addKeyListener(this);
setDoubleBuffered(true);
}
@Override
public void paintComponent(Graphics g) {
AffineTransform saveTransform;
final Graphics2D g2 = (Graphics2D) g;
g.clearRect(0, 0, this.getWidth(), this.getHeight());
Rectangle rect = new Rectangle(20, 20);
g2.rotate(Math.toRadians(rotation), rect.height / 2, rect.width / 2);
g2.translate(x, y);
g2.draw(rect);
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);
}
public void keyTyped(KeyEvent e) {
}
/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
x = x - 5;
repaint();
break;
case KeyEvent.VK_RIGHT:
x = x + 5;
repaint();
break;
case KeyEvent.VK_UP:
y = y - 5;
repaint();
break;
case KeyEvent.VK_DOWN:
y = y + 5;
repaint();
break;
case KeyEvent.VK_X:
rotation++;
repaint();
break;
case KeyEvent.VK_Z:
rotation--;
repaint();
break;
}
}
public void keyReleased(KeyEvent e) {
}
}