Home » Java programs » Java applet programs

Java Applet program to show the animation of a bouncing ball



Here, we are implementing a java program that will display an animation of bouncing ball. This is an example of java applet program.
Submitted by Chandra Shekhar, on January 11, 2018

Given coordinates of the box, radius of the circle and color using these elements we have to make an animation of a bouncing ball using Java applet program.

Applet program to show animation of bouncing ball

// This java applet program will show the bouncing balls

package Applet;

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

public class BouncingBall extends Applet implements Runnable 
{
	// x,y coordinates and radius of the circle.
	int x = 150, y = 50, r=20;   
	int dx = 11, dy = 7;          
	
	// create thread.
	Thread t;
	boolean stopFlag;

	// Function to start thread.
	public void start() 
	{
		t = new Thread(this);
		stopFlag=false; 
		t.start();
	}

	// Draw cicle from its present position.
	public void paint(Graphics g) 
	{
		g.setColor(Color.red);
		g.fillOval(x-r, y-r, r*2, r*2);
	}

	// function to move the image.
	public void run() 
	{
		while(true)
		{
			if(stopFlag)
				break;
			// Bounce if we've hit an edge.
			if ((x - r + dx < 0) || (x + r + dx > bounds().width)) dx = -dx;
			if ((y - r + dy < 0) || (y + r + dy > bounds().height)) dy = -dy;
			// Move the circle.
			x += dx;  y += dy;

			try
			{
				Thread.sleep(100);
			}
			catch(Exception e)
			{
				System.out.println(e);
			};
			// print circle again n again.
			repaint();
		}
	}

	// function to stop printing.
	public void stop()
	{
		stopFlag=true;
		t=null;
	}
}

Output

Bouncing ball java applet program





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.