How to rotate the square in my swing app

1k Views Asked by At

I have developed a little swing application in which i have drawn a square.Now i want to rotate this square at its center using Thread.The problem i'm having is how to get reference to that square in my rotateSquare() method. (Actually i need a method,if possible, to rotate the same square instead of wiping out the entire content pane and drawing another rotated square at its position).

Here is my code:

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class Rotation extends JFrame implements Runnable{
Thread t;
Rotation()
{
    super("Animation of rotation about center");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400,400);

    setContentPane(new Container(){
        public void paint(Graphics g)
        {
            Graphics2D g2=(Graphics2D)g.create();
            g2.setBackground(Color.WHITE);
            g2.clearRect(0, 0, getWidth(), getHeight());

            g2.setColor(Color.GRAY);
            g2.fillRect(100, 100, 100, 100);
        }
    });

    t=new Thread(this,"pr");
    t.start();


    setVisible(true);
    //setOpacity(0.8f);
}
public void run()
{
    try{
        for(;;)
        {
            Thread.sleep(100);
            SwingUtilities.invokeLater(new Runnable(){public void run(){
                rotateSquare();
            }});
        }
    }catch(InterruptedException e){System.out.println("Thread interrupted");}
}
public void rotateSquare();
{

}
public static void main(String args[])
{
    //setDefaultLookAndFeelDecorated(true);
    SwingUtilities.invokeLater(new Runnable(){public void run(){new Rotation();}});
}

}
2

There are 2 best solutions below

2
On BEST ANSWER
0
On

You should define a Square class that would include code defining a square object. This would have a draw(Graphics g) method that would know how to draw the Square.

In your other class, you would have a reference to a Square object. Under the paint method you would call square.draw(g).

This way, you can apply the rotation under the Square draw() method.