Wednesday, 11 January 2012

Rotate a Semi Circle in Java applet using Runnable Interface

Create a java file name RotateCircle.java as below



/*  Program to draw  a square and rotate a semi circle*/

// Import this two packages to use applet and awt classes
import java.applet.*;
import java.awt.*;


//The following code is written to run the applet window in 500 height and 500 width

/*   <applet code="RotateCircle.java" height=500 width=500>
</applet>   */

public class RotateCircle extends Applet implements Runnable
{
public void init()
{
                  //Creating thread by passing class which implements Runnable interface as a parameter
         Thread t = new Thread(new RotateCircle());
}

public void paint(Graphics g)
{
        // It draws a square with black color


                   g.setColor(Color.black);
         g.fillRect(15,15,100,100);
     
       // This loop is running for drawing and rotating the semicircles

      for(int ifor=0;ifor<360;ifor+=25)
     {
      //It draws gray color arc on the applet
        g.setColor(Color.gray);
                g.fillArc(200,25,100,100,ifor,360);

      //I have drawn white arc to give a feel that arc (semi circle) is rotating
      g.setColor(Color.white);
      g.fillArc(200,25,100,100,ifor,180);

                      try
     {
           // This code is to make the thread sleep for 2 seconds
               Thread.sleep(2000);
              }
     catch(InterruptedException e)
    {
    //catching exception if the thread is interrupted
    }

            // repaint() method is used here to repaints the window each time the loop iterates
             repaint();
     }             
}

//It is a blank implementation of run method
public void run()   {   }
}

Compile the above java file in the command prompt


C:\Java>javac Ex_Rotate.java


Run the appletviewer

C:\Java>appletviewer Ex_Rotate.java


The applet window will be opened and the circle shown below will be rotating on your applet window








5 comments: