FootnotesTopCreating and Drawing ImagesCreating simple animations

Creating simple animations

Animations take a bit of work, as they require a separate thread to do the updating of the picture that is different from the thread that is actually doing the drawing and responding to other events. The following is a description of a low overhead way of doing animation that relies on events fired by a timer rather than creating a separate thread (which we will talk about later in the term). See the program SimpleTimerAnimation for a simple example of an application that creates an animation using a Timer object.

  1. In the constructor for the main class (the one that extends JFrame), insert commands of the form
            Timer myTimer = new Timer(interval,this);
            myTimer.start();
        

    This creates a timer that will generate an ActionEvent every interval milliseconds (which is 1/1000 second). The timer can be turned off by sending it a stop() message.

  2. The constructor given above creates a timer that expects the object that created the timer to respond to the timer events. To be notified that the timer has gone off the class must implement the interface ActionListener. Therefore the header of the class should look like:
            public class MyClass extends JFrame implements ActionListener {
        

    The interface ActionListener has a single method:

            public void actionPerformed(ActionEvent evt);
        

    that the class must implement.

  3. Each time the timer is fired (using whatever interval was chosen when the timer was created), the method actionPerformed will be called. The value of the formal parameter evt will be the timer event that triggered the call. It is rarely needed in the method body, so you may ignore it for now, though it must appear as a formal parameter of the method. The body of the method should include whatever is necessary to update the state of all of the objects and then call repaint().
  4. As before, repaint() will end up calling paint(Graphics g). That routine is responsible for doing all of the actual draw or fill commands. Of course that method can itself call draw routines for objects that are in your program. For example, in a program with several gardens, the paint method can send a draw(Graphics g) message to each of the gardens, where the corresponding method draws all of the plants in the garden.
  5. In order to clear the screen between invocations of paint, I found it necessary to call super.paint(g) at the beginning of the paint method. I believe this is necessary so that all the subcomponents also get repainted properly. When this was not done, the earlier images were not erased.

FootnotesTopCreating and Drawing ImagesCreating simple animations