1

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();}});
}

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

3
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • can anyone please type a bit of code so that i know exactly what to do as i'm not much experienced with Java 2D Graphics. – Naveen Oct 24 '12 at 12:31
  • `Timer` is alternative to `Thread`, for [example](http://stackoverflow.com/a/3420651/230513). – trashgod Oct 24 '12 at 16:53
0

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.

Dan D.
  • 32,246
  • 5
  • 63
  • 79