Images are treated different, an image is not regarded as a stream of bits, but
as a single object by itself. Therefore, there is a class Image
in java.awt, and
there is a method
getImage(URL url, String filename)
in java.applet.Applet. For example, the applet below displays just an image located in the subdirectory "IO".
import java.awt.*; import java.net.*; import java.applet.Applet; public class ImageExample extends Applet { Image img; String filename = "100percentstatic.gif"; public void init ( ) { img = getImage(getDocumentBase(), filename); } public void paint (Graphics g) { g.drawImage(img, 0, 0, this); } }
As loading images over the network often takes some time, the method
getImage
returns immediately, so it does not wait for the complete image to be loaded.
A separate thread takes care of the loading, and the application does not
loose time.
This separate loading works fine and efficient, but there is some payoff as
at some point the applet or the programmer has to know that the image is completely loaded.
ImageObserver
whose sole function is to notify the applet about
the status of the graphics. In particular the applet should know when the
image is complete. The last argument
this
of
drawImage refers to the applet as ImageObserver.MediaTracker
, whose purpose is to keep track of the
status of a different kinds of media. The programmer can make the program wait for
the images to be loaded with help of this tracker. We used this for instance
in the animation of the chapter
on Threads.