7.3.5 Images

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.