Special Effects and Game Development
in Java(TM) -Improve the image loading with MediaTracker
by Anibal Wainstein
4.0.2 Improve the image
loading with MediaTracker
Did you notice that you could practically see the image being
loaded in the last section's example? This was because the
paint() method is called several times during the image
download! The reason that Sun chose to make the system
this way, is that they wanted to keep the effect of seeing
something while waiting for a page to download. This was usual
in older web browsers (new web browsers such as IE4.0, will
only display the image when it is fully downloaded, unless
it does not happen to be an interlaced GIF image). The paint()
method will be called arbitrary by the web browser when it
has managed to download a new piece of the image. This could
cause problems and can look bad in some applets. But there
is a solution, there is a class named MediaTracker, which
makes sure that the image is fully downloaded before you use
it.
Let us rewrite the init() method in the last section to:
public void init()
{
logo=getImage(getDocumentBase(),"logo.jpg"); //The following line creates a tracker.
MediaTracker tracker=new MediaTracker(this); //We give the image we want to track the
//identification number 0.
tracker.addImage(logo,0); //With the waitForAll() method the image can
//be loaded. It will throw an InterrupterException
//if something happens. try
{
tracker.waitForAll();
} catch(InterruptedException e)
{ System.out.println("Something happened while reading image...");
}
}
A tracker object requires a reference to the applet when
it is created (you get that with "this"). With the
addImage() method we can give the image the ID number 0, in
the methods internal "download list". Please note
that you cannot give several images the same ID number, each
must have a unique number. Finally, we can use the waitForAll()
method that makes sure to load all the images. This method
throws an exception
that you must "catch".
Click here to see an
improved version of the last section's applet. In this example
the difference is minimal and maybe not even noticeable, but
in more complicated graphics applets it is a necessity.
Next Page >>
|
 |  |
|