CSC 120 Animation Overview - Fall 2005

[Course home page]

The following is a skeleton for a component class supporting animation. Basically, the steps are:

  1. Add appropriate imports
  2. Class should implement the ActionListener interface
  3. Add a timer field to the class
  4. Add an animate() method that sets up the timer and starts it going
  5. Fill in an actionPerformed() method with code to update the state of the object on each step of the animation. The repaint() method is usually called in the actionPerformed() in order to make sure the updated state of the object is displayed in the component. (Remember, components will usually also have a paintComponent() method to draw graphics in the component.)

 

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.Timer;

public class ComponentName
  extends JComponent
  implements ActionListener {

   private Timer timer;            // timer instance variable
   . . . // other instance variables (fields)

   . . .
   
   /**
    Starts the timer going by constructing a Timer object with the 
    frequency (in milliseconds) of Timer activations and the object ('this')
    that will be handling the Timer events
    */
   public void animate() {
      timer = new Timer( (int)Math.round(deltaT * 1000), this );
      timer.start();
   }
   
   /**
    Processes a Timer activation event
    */
   public void actionPerformed( ActionEvent e ) {
      // Code to update the state of the object
      // should go here
      . . .

      repaint();     // repaint the component on the screen
   }

}
	

 



Berry College