Reviews : Java Books :
Beginning Java 2- JDK 1.3 Version : Images and Animation

Buy this book
Title: Beginning Java 2- JDK 1.3 Version
ISBN: 1861003668
US Price: $ 49.99
Canadian Price:
C$ 74.95
UK Price: £ 35.99
Publication Date: March 2000
Pages: 1230
© Wrox Press Limited, US and UK.

Beginning Java 2- JDK 1.3 Version
Images and Animation

Try It Out – Using a Timer

Much of the code will be the same so we will only repeat the essentials here. The class no longer needs to implement the Runnable interface so the run() method is no longer required in the applet class.

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.net.*;
import java.awt.geom.*; // For AffineTransform

public class TimedWhirlingLogo extends JApplet
{
 
  // This method is called when the applet is loaded
  public void init()
  {
    // Code exactly as before...
  }
    // This method is called when the browser starts the applet
  public void start()
  {
    if(tracker.isErrorAny()) // If any image errors
      return; // don't create the thread

    timer = new java.util.Timer(true);
    timer.schedule(new java.util.TimerTask()
             {
               public void run()
               {
                 imagePanel.repaint(); // Repaint the image
                 angle = 2.0*Math.PI*stepCount++/STEPS_PER_ROTATION;
                 stepCount = ++stepCount%STEPS_PER_ROTATION;
                }
              },
              0, INTERVAL);
}
    // This method is called when the browser wants to stop the applet 
    //  - when is it not visible for example
    public void stop()
    {
      timer.cancel();
    }

   // Class representing a panel displaying an image
   class ImagePanel extends JPanel
   {
     // Code exactly as before...
   )

  java.util.Timer timer; // Animation timer
  MediaTracker tracker; // Tracks image loading
  ImagePanel imagePanel;
  AffineTransform at = new AffineTransform();
  int imageWidth, imageHeight; // Image dimensions
  double angle;  // Rotation angle 
  final int INTERVAL = 50;  // Time interval msec
  final int ROTATION_TIME = 2000;  // Complete rotation time msec
  final int STEPS_PER_ROTATION = ROTATION_TIME/ INTERVAL;
  int stepCount; // Total number of steps
}

If you compile and run this applet, it should run just as well as the previous version.

How It Works

The code is a lot shorter because the Timer object does all the scheduling work. The start() method in our applet class creates the Timer object we will use to schedule the animation with the statement:

 
timer = new java.util.Timer(true);

The variable, timer, is a member of the TimedWhirlingLogo class rather than a variable local to the start() method because we also need to reference it in the stop() method. Note how we have used the fully qualified name for the Timer class here, and in the declaration of timer as a member of the applet class. This is essential in this case. Importing the package, java.util, containing the Timer class would not be sufficient. As we said earlier, the javax.swing package also defines a class with the name, Timer, so without qualification of the name, the compiler would be unable to decide which class we wanted to use.

We then use the Timer object to schedule the animation with the statement:

timer.schedule(new java.util.TimerTask()
      {
         public void run()
         {
            imagePanel.repaint();  // Repaint the image
            angle = 2.0*Math.PI*stepCount++/STEPS_PER_ROTATION;
            stepCount = ++stepCount%STEPS_PER_ROTATION;
          }
          },
          0, INTERVAL);

We use the schedule() method here because we need the task to be executed at evenly distributed intervals to get a smooth animation. The first argument to the schedule() method is defined by an anonymous class derived from TimerTask. We again use a fully qualified class name here – not because there is a duplicate use of the name, but because we have not imported the java.util package into our source file. The run() method  in our anonymous class specifies the task to be executed. This consists of two steps: redrawing imagePanel containing the logo, and updating angle that determines the orientation of the logo next time around. The second argument to schedule() specifies a delay of zero milliseconds before the first execution of the task, so the animation will begin immediately. The third argument specifies the interval between successive frames of the animation. Defining the constant, INTERVAL, as a member of the applet class enables it to be referenced as an argument to the schedule() method and within the run() method of the anonymous class.

That's it. Using Timer objects makes scheduling animations a lot simpler. Let's try one more example to get a feel for using the scheduleAtFixedRate() method.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.