Wednesday, June 19, 2013

Program for moving circle up and down on a line using java

//<applet code=Thread2 width=700 height=600></applet>
import java.applet.*;
import java.awt.*;
public class Thread2 extends Applet implements Runnable // Runnable is interface for class Thread.It will help in overriding run() function
{
  int y,flag;
  Thread t;
public void init()
  {
  y=0;
    t=new Thread(this);
    t.start();     // calls run() function
  }
  public void run()  // run() function overridden
  {
    while(true)    //runs infinite loop
    {
      if(y==0) flag=0;
      if(y==350) flag=1;

      if(flag==0) y+=5;
      if(flag==1) y-=5;
      repaint(); // calls paint() with new values. Previous Screen goes to clear.
      try
      {
        Thread.sleep(20); // 100 is milli second, sleep is static function of class Thread that makes control flow delay for a given millisecond.
      }
      catch(InterruptedException er)
      {
        System.out.println("Unable to run sleep function");
      }
    }
  }
public void paint(Graphics g)
  {
    g.drawOval(300,y,50,50);   // draw circle of width=height=50
    g.drawLine(200,400,500,400);  // draw line of length 100
}
}
Facebook Blogger Plugin: Bloggerized by Software Tips Enhanced by Akash Parnami

Leave a Reply