Press "Enter" to skip to content

Java Program for Moving Ball using Applet

Program Abstraction:
        This Java program code shows an output of animated moving ball with applet.

This is a simple and funny java applet program for an animated free hand moving ball. Actually it is not a ball; it is rounded oval, filled with color black. This ball will bounce continuously without any pause or stop. You have to close your applet viewer or browser to stop the movement of this unstoppable moving ball. That is, here infinity loops are used.

We made this program using applet, you can do this program in ‘Frame’ by extending frame. Then you have to write code for main for this program.
(Learn how to make and run a java applet program).

Program code for Moving Ball:

import java.applet.*;
import java.awt.*;

 /* <applet code = "ball" width = 400 height = 200> </applet> */
public class ball extends Applet implements Runnable
 {
 Thread t;
 int x = 0;
 int y = 0;

public void start()
 {
 t = new Thread(this);
 t.start();
 }

public void paint(Graphics g)
   {
      g.fillOval(x,y,100,100);
    }

public void run()
 {
   try
      {
      for(;;)
       {
                for(;;)
            {
                 if(y == 120)
                     {
                      break;
                     }
    else if (x == 390)
        {
     x = 0;
     y = 0;
    repaint();
         }
             else
               {
                   y = y +3;
                   x = x +3;
                   Thread.sleep(100);
                 repaint();
               }
                }
           for(;;)
              {
               if(y==0)
                   {
                        break;
                        }
               else if (x == 390)
           {
          x = 0;
          y = 0;
                 repaint();
    }
    else
                 {
        y = y-3;
               x = x +3;
               Thread.sleep(100);
                repaint();
               }
                } 
            run();
       }
  }

catch(InterruptedException e)
    {

    }
 }
}

Sample Output:

Java Program for Moving Ball with Applet

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *