You are here:

Java/Java applet for bouncing balls


Hi I have created an applet for an assignment that has bouncing balls within a frame. However I need these to now bounce of each other, or collide if you will. However I am not able to do this!

Any help appreciated!!

Original code below  WARNING applet flickers, cant get it to stop so if you have epilepsy dont open it!

import java.awt.*;
import java.awt.image.ImageObserver;
import java.util.*;

  class Ball{
       protected int radius = 20;
       protected int x, y;
       protected int dx = 2, dy = 4;
       protected int width, height;
       protected Image image;
       public final Random generator = new Random();
       Color bColour;
       public static int delay = 100;
       Graphics g;
       public Ball(Color c, int width, int height){
      int max = width - radius;
      int maxh = height - radius;
      int min = 0 + radius;
      x = (int) ( min + (Math.random() * (max - min)));
      y = (int) ( min + (Math.random() * (maxh - min)));
    double w = Math.random();
      if (w >= .5)
         dx = generator.nextInt(10)+4;
         dy = generator.nextInt(10)+4;
      else {
         dx = generator.nextInt(10)+4 *-1 ;
         dy = generator.nextInt(10)+4 *-1;
      bColour = c;

       public void movement(int widthsc, int heightsc)
         width = widthsc;
         height = heightsc;
         if (x < radius || x > width - radius) {
         dx  =  -dx;
         if (y < radius || y > height - radius) {
         dy  =  -dy;
         x += dx;
         y += dy;
       public void paint(Graphics graphball ){
         g = graphball;
         g.fillOval(x - radius, y - radius,
         radius * 2, radius * 2);


public class bounceBalls
   extends java.applet.Applet implements Runnable {

protected Color color =;
 protected int numBalls;
 Ball balls[];
 private Color Colors[] = {Color.GRAY, Color.BLUE, Color.ORANGE, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.GREEN, Color.PINK, Color.YELLOW, Color.RED};
 private int c; //count colours
 protected Thread bouncingThread = null;
 protected int x, y;
 protected Image image;
 protected Graphics offscreen;
 private final Random generator = new Random();
 public void init() {
        image = createImage(getWidth(), getHeight());
        offscreen = image.getGraphics();
        numBalls = Integer.parseInt(getParameter("balls"));
        balls = new Ball[numBalls];
    for (int i = 0; i< numBalls; i++)
       if (c>=10)
         c = generator.nextInt(9);
       balls[i] = new Ball(Colors[c], getWidth(), getHeight());
 public void start() {
    if (bouncingThread == null){
   bouncingThread = new Thread(this);

 public void run() {
      while (true) {
        try {
        } catch (InterruptedException  e) {}
         for (int j =0; j< numBalls; j++)
         balls[j].movement(getWidth(), getHeight());
 public void paint(Graphics g) {
        offscreen.fillRect(0,0,getWidth(), getHeight());
        for (int z = 0; z<numBalls; z++)
         g.drawImage(image,0,0, this);


This is a bit more complex than bouncing off of walls as you need to determine 2 things:
1. Which balls if any are bouncing off each other?
2. What angle do they rebound at?

1. If you have a few balls (less than 20) then you can store your balls as Ellipse2D.Double. Then use the Area class to wrap each Ellipse2D.Double. Finally you can use intersect to create an intersection and determine if that intersection is empty.

2. There are various ways to emulate the physics of this, but a simple way is to exchange the velocity of the two balls. This will look a bit odd as two balls comming directly at each other, but offset, will simply rebound in the oppset direction.
E.g. (define a shape variable in the ball code that holds and updates the ball's shape.

for(int i = 0; i < balls.length; i++)
  for(int j = i + 1; j < balls.length; j++)
     Area area1 = new Area(balls[i].shape);
     Area area2 = new Area(balls[j].shape);
        int ball1Dx = ball1.dx;
        int ball1Dy = ball1.dy;
        ball1.dx = ball2.dx;
        ball1.dy =;
        ball2.dx = ball1Dx;
        ball2.dy = ball2Dy;


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.


I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Washington State University

MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 All rights reserved.