Java 1.2/Swing Bouncing Animations
I use the following files (also available on acpub
in ~ola/cps108/java/boncy).
- Bouncy2.java the main program, the
animation panel, the Gui, a bouncer and a quitter (too many classes in
one file).
- TapImage.java a class for displaying
images (loaded from a jar file).
- ImageLoader.java loads images from a
jar file.
- gif.jar two gifs taht can be used, their use
in Bouncy2.java is commented out in the code here.
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
- 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).
- 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).
- 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