Java Animation Flickering

March 16, 2011 | Animation

Animation is very easy in Java and it is the place where you can prove Java is a simple language to practice. Flickering is a very big constraint in animation coding and techniques of overcoming is illustrated. Java Animation Flickering is discussed elaborately with screenshots.

Introduction to Java Animation Flickering

Animation, an inevitable feature of multimedia, includes a movement of a number of images sequentially with a controlled interval of time. Even though, the images are shown rapidly one-by-one, the eye does not catch the lapse period. The fixation of interval of time is very important; else, jumping of images occurs. Cartoons are good examples of animation.

Requirements for Animation
  1. A group of images with relevant postures.
  2. Create a separate thread to run the animation.
  3. Use MediaTracker to take care of image loading.

The following animation program requires a bunch of images with related postures. When you load JDK, you get 10 images, T1.gif to T10.gif; the images display the word "Java". To manage the images, the images are placed in an array, i1[], so that they can be called with their index numbers easily in a for loop. A time interval of 510 milliseconds is taken for a smooth animation. repaint() method is called for every iteration to override the earlier image drawn.

import java.awt.*;
import java.applet.*;   
public class JavaAnimation extends Applet implements Runnable   
  MediaTracker mtrack; 			
  Thread  t1 ;   				   
  Image i1[];
  int frame = 1;	
  public void init()   
    mtrack = new MediaTracker(this);                     
    i1 = new Image[10] ;  

    for(int i=0; i<i1.length; i++)="" {="" i1[i]="getImage(getDocumentBase()," "t"="" +="" i="" ".gif="" ");="" mtrack.addimage(i1[i],="" 0);="" }="" public="" void="" start()="" if(t1="=" null)="" t1="new" thread(this);="" t1.start();="" run()="" while(true)="" try="" mtrack.waitforid(0);="" catch(interruptedexception="" e)="" return;="" if(++frame=""> 9) 				            
        frame = 0;
      catch(InterruptedException e)  
  public void paint(Graphics g)   
    g.drawImage(i1[frame], 60, 60, this) ;
    showStatus("Animation is Running" ) ;

HTML to run the animation applet: JavaAnimation.html

Java Animation Flickering Output screen on Animation Flickering Java

mtrack = new MediaTracker(this);

A MediaTracker object, mtrack, is created to monitor the images. The parameter "this" represents an object of ImageObserver.

i1[i] = getImage(getDocumentBase(), "T" + i + ".gif"); mtrack.addImage(i1[i], 0);