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();}});
}
}
see AffineTransform
add parameters AffineTransform.rotate(intDegrees);
fit rotated Object to the parents bounds myAffineTransform.translate(getWidth(), getHeight())
then returns back Graphics2D#transform(myAffineTransform);
use Swing Timer instead of Runnable#Thread
with Thread.sleep(int)
, that caused freeze or flickering for Graphics2D and locked EventDispatchThread untill endless Thread
ended (never ending in your case)