I have developed a little Swing application in which i have added a Square into my JFrame
using a separate class component
. Now i want to rotate this Square at its center, but I am only seeing a static Square which is not rotating at all.
This is my code...
public class Rotation extends JFrame {
Rotation() {
super("Animation of rotation about center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
add(new component());
setVisible(true);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){public void run(){new Rotation();}});
}
}
class component extends JPanel implements ActionListener {
Timer timer;
Rectangle.Double r=new Rectangle.Double(100,100,50,50);
int theta=0;
component() {
timer=new Timer(10,this);
timer.start();
}
public void actionPerformed(ActionEvent e) {
if (theta==360){
theta=0;
theta++;
}
repaint();
}
public void paint(Graphics g){
Graphics2D g2=(Graphics2D)g;
g2.setColor(Color.GRAY);
g2.rotate(theta);
g2.fill(r);
}
}
Could someone please help me identify and fix the problem.
the problem was that i needed to make 2 changes:
// 1.
g2.rotate(theta,125,125);
// 2.
super.paint(g);