Bouncing Ball Corrections
Fall 2006, David Matuszek

Minor correction to ball movement

Balls are supposed to start with initial deltaX and deltaY values that are between -4 and +4. I did the arithmetic wrong. In the Ball class I say:

  this.deltaX = random.nextInt(9) - 5; // choose an x speed in range -4..+4
  this.deltaY = random.nextInt(9) - 5; // choose a y speed in range -4..+4 
but it should be:
  this.deltaX = random.nextInt(9) - 4; // choose an x speed in range -4..+4
  this.deltaY = random.nextInt(9) - 4; // choose a y speed in range -4..+4 

Better access to the Graphics g

In the BouncingBalls class I defined g inside the run method:

    Graphics g = panel.getGraphics(); // Gets the Graphics context

As you should recall, a variable declared in a method is only available in a method. To make it available to other methods, you need to pass it in as a parameter:

  someOtherMethod(g);

or (better) you need to split the declaration and the initialization: Declare it in the class, and give it an initial value in the run method, like so:

  public class BouncingBalls extends JFrame {
      Graphics g;
      ...
      void run() {
          ...
          g = panel.getGraphics(); // Gets the Graphics context
          ...

      }
      ...
  }

Balls not appearing on the screen

This one is weird. The first time you do a pause(), everything you drew up to that point disappears from the panel, usually before you can even see it was there. If you have this problem, simply put a pause(); statement immediately after the g = panel.getGraphics(); statement in your run method.

Of course, there are lots of things you could be doing wrong that would cause the balls not to appear, starting with forgetting to draw them. If adding the pause() doesn't work for you, your problem is most likely elsewhere.