Java 1.2/Swing Bouncing Animations

I use the following files (also available on acpub in  ~ola/cps108/java/boncy).

To run the program type (Unix)

   javac -classpath ".:gif.jar" Bouncy2.java

On Windows machines a semi-colon is the path separator rather than a colon so type

   javac -classpath ".;gif.jar" Bouncy2.java

Absolute Coordinates

The JPanel extended by the BouncerPanel class is given a null Layout manager. Since there is no layout manager, objects can draw themselves at absolute coordinates and these coordinates will work.

The key ideas needed in addition to the null layout manager are

  1. In animated (or fixed) objects the paintComponent method should draw into the passed-in Graphics objects using absolute coordinates, e.g.,
            g.setColor(myColor);
    	g.fillOval(myX,myY,DIAMETER,DIAMETER);
    
    Which is different from when a layout manager is used (my original code uses 0,0 for drawing coordinates, but uses setLocation and getBounds to let the panels/containers "know" where an object is).

  2. I don't use setLocation to force an ojbect to move/get redrawn. Instead, the BouncerPanel explictly invokes an object's painting method by firing doDraw on all contained objects (see the panel's paintComponent).

    I'm not sure why this is needed, but it is, the Panel won't draw it's children when the panel is repainted, this is most likely due to interactions with the non-existent layout manager (or lack of interactions).

  3. In the code shown I have paintComponent call doDraw, this use of the template pattern, in which doDraw is a hook method, made it simpler to implement ImageBouncer as an extension of Bouncer. Since an object's paintComponent in general should invoke super.paintComponent, I moved the drawing out of paintComponent so that subclasses can specialize drawing without drawing the parent class.

Owen L. Astrachan
Last modified: Wed Nov 17 22:48:35 EST 1999