Bouncing ball applet – Create Balls on Mouse click of random color and random size

In previous example, we have seen that how to animate two balls around the applet border.

In this section, we will create ball of random size, random speed and random color on mouse click.

To create a random number we have used Math.random().

To create a random number between 1 and 256, we have to multiply it by 256. 256 * Math.random().

On every mouse click we have added the object of ball in List and every time in run method and paint method, we have iterate over the list and applied the logic

Bouncing Ball applet - Create ball on Mouse click of random size and random color

package com.shivasoft;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

class Ball
{
int x,y,radius,dx,dy;
Color Ballcolor;
/**
*
* @param starting x position
* @param starting y position
* @param radius
* @param x displacement
* @param y displacement
* @param ball Color
*/
public Ball(int x,int y,int radius,int dx, int dy, Color bColor)
{
this.x = x;
this.y = y;
this.radius = radius;
this.dx = dx;
this.dy = dy;
Ballcolor = bColor;
}
}

public class BouncingBall extends Applet implements Runnable,MouseListener {

List bCollection;
public void init()
{
bCollection = new ArrayList();

Thread t = new Thread(this);
t.start();
addMouseListener(this);
}
public void paint(Graphics g)
{
for(Ball b : bCollection)
{
g.setColor(b.Ballcolor);
g.fillOval(b.x, b.y, b.radius, b.radius);
}
}
public void run()
{
while(true)//infinite loop
{
try
{
for(Ball b : bCollection)
{
displacementOperation(b);
}
Thread.sleep(20);
repaint();
}catch(Exception e)
{

}
}
}
public void displacementOperation(Ball ball)
{
if(ball.y <= 0 || ball.y >= 200)
{
ball.dy = -ball.dy;
}
if(ball.x <= 0 || ball.x >= 200)
{
ball.dx = -ball.dx;
}

ball.y = ball.y - ball.dy;
ball.x = ball.x - ball.dx;
}
@Override
public void mouseClicked(MouseEvent evt) {
int r,g,b;

r = (int)(255 * Math.random());
g = (int)(255 * Math.random());
b = (int)(255 * Math.random());

Color c = new Color(r,g,b);

int radius = (int)(20*Math.random());

int dx = (int)(5*Math.random());
int dy = (int)(5*Math.random());

Ball ba = new Ball(evt.getX(),evt.getY(),radius,dx, dy, c);
bCollection.add(ba);

}
@Override
public void mouseEntered(MouseEvent evt) {

}
@Override
public void mouseExited(MouseEvent evt) {
}
@Override
public void mousePressed(MouseEvent evt) {
}
@Override
public void mouseReleased(MouseEvent evt) {
}
}

Posted

in

by

Tags:


Related Posts

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading