The KeyboardAnimation2 applet provides a generic framework for applets
both display an animation and respond to keyboard events. The animation
runs only when the applet has the keyboard focus and can respond to
key presses. The appearance of the applet changes, depending on whether
it has the keyboard focus. Note that each time a new frame of the
animation is to be displayed, it is drawn completely from scratch.
When the applet has the keyboard focus, a cyan border is drawn around
it. When it does not have the keyboard focus, the border is in
the applet’s background color and a message “Click to activate” is
displayed in the applet’s foreground color and font.

This class would be appropriate, for example, as a basis for a typical
arcade game, such as Space Invaders. (Except that the performance
might not be good on a slow machine.)

To use this framework, define a subclass of KeyboardAnimationApplet2 and
override the drawFrame() method. This method is responsible for drawing
one frame of the animation. If you need to some initialization at the
time the applet is created, override the doInitialization() method.
This method is called once when the applet is created. You should
not override the standard applet methods init(), start(), and stop()
unless you call the inherited versions from this class.

In this class, the applet is already set up to “listen” for keyboard
events. To make your applet respond to keyboard events, you should
override one or more of the methods keyPressed(), keyReleased(),
and keyTyped(). The applet also listens for MouseEvents, and you
can override the mouse handling events if you want. But if you do
override mousePressed(), be sure to call super.mousePressed() which
will request the input focus.

To respond to key presses, you should have some instance variables
that affect the image drawn. Change these variables in the keyPressed,
keyReleased, or keyTyped methods.

(Alternatively, instead of defining a subclass, you could copy this
file, change its name and the name of the class, and edit it.)

When this file is compiled, two class files are produced:
KeyboardAnimationApplet2.class and KeyboardAnimationApplet2$1.class.
Both class files are necessary to use the applet.

David Eck
Department of Mathematics and Computer Science
Hobart and William Smith Colleges
Geneva, NY 14456

May 20, 2002

NOTE: This program requires Java 1.2 or higher. It is based on an older
program,, which has essentially the same
functionality but which worked with Java 1.1.