JavaRanch Home    
 
This page:         last edited 15 October 2007         What's Changed?         Edit
READ ONLY

Code Barn Load A Gif   

You must turn on Java for applets to work.

Explanation of LoadAGif applet

Number of files: 2 (LoadAGif.class, and a .gif file named horsenav.gif)

What it does: Displays an .gif image in an applet. The image is fully downloaded before being displayed.

How to display a gif file in an applet:

  1. Create an instance of Image
  2. Create an instance of MediaTracker
  3. Add the Image to the MediaTracker instance
  4. Call the MediaTracker object's waitForAll() method. The method will block until the image is fully downloaded.
  5. Override the applet's paint() method, and add a method call to drawImage().

You may skip steps 2, 3 and 4 if you don't mind that the paint() method will attempt to draw the image before it is fully downloaded.

A JavaDoc:java.awt.MediaTracker is just what the name suggests -- an object whose job is to track the download status of media elements. Sadly, it was implemented only for Images. Originally, it was designed to allow adding other media, such as audio files. So a more realistic name would be ImageTracker : (

You can do more sophisticated status-checking with MediaTracker, to implement a status bar, for example.


Code


import java.applet.* ;
import java.awt.* ;
    
public class LoadAGif extends Applet 
{
    private Image myImage ;

    init() 
    {
        myImage = getImage( getCodeBase() , "horsenav.gif" );
        // use a MediaTracker so the image will be downloaded
        // completely before being displayed
        MediaTracker mt = new MediaTrackerthis );
        mt.addImage( myImage , 0 );

        try
        {
            mt.waitForAll(); // blocks here until Image is fully downloaded
        }
        catch ( InterruptedException e ) 
        {
        }
    }// close init

    public void paint( Graphics g ) 
    {
        g.drawImage( myImage , 25 , 25 , this );
    }// close paint
}// close applet


CodeBarnApplets

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton