How do I display an Image in an applet or application?
g.drawImage(image, xPosition, yPosition, this);The last argument is what's called an ImageObserver and helps deal with the asynchronous loading of image data. Generally speaking, you just pass a reference to the applet as the image observer so that as more data is loaded the applet (the observer) is notified and redraws itself.
This leaves one question though. How do you get the image to display? The getImage() method of Applet or Toolkit helps here, requiring just the URL of where to get the image from:
Toolkit kit = Toolkit.getDefaultToolkit();
Image image = kit.getImage(url);
Image image = kit.getImage(filename);
Image image = getImage(baseURL, file);Here, you provide the base URL and filename separately. The two are combined to form the specific URL to get the image file from. How is this better? Well, there are two more methods to help here. The getDocumentBase() method allows you to start with a base URL of where the HTML file is located. And, the getCodeBase() method allows you to start with a base URL of where the .class file is located. Using one of the two you can find an image in the same directory as either with something like this:
Image image = getImage(getDocumentBase(), "image.jpg");That is basically it, except if you want to package image files into a JAR. For this, you need to use the getResourceAsStream() method of the Class class.
InputStream in = getClass().getResourceAsStream ("image.gif"); byte buffer = new byte[in.available()]; for (int i = 0, n = in.available(); i<n; i++) buffer[i] = (byte)in.read(); // in.read(buffer); // this doesn't read all when reading from JAR Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.createImage(buffer);Unfortunately, you cannot use the getResource() method (which returns a URL) as Netscape browsers do not support it.