Applet Background Image

Displaying backgound Image in an Applet is a two step process.

First - Get the handle to the image using a simplified method getImage() or using the MediaTracker API. This is done in the Applet's init() method. Using the Media Tracker provides more events/notification that can handled ex.failed to load the media, etc.

Also with Media Tracker a variety of resource types can be retrieved not just image.

Finally - Once the image handle is there, draw the image at a given location in the Applet's paint(..) method with the drawImage(image,x,y, this) method.

The image can of any format like jpg, gif, png etc.


package com.livrona.snippets.applet;

import javax.swing.*;
import java.awt.*;

/**
* This snippet shows how to load background image in the Applet
* @author mvohra
*
*/

public class DisplayImageApplet extends JApplet {
private static final long serialVersionUID = -5674243667829955526L;

private Image im; // image handler
private static final String IMAGE = "background.gif";

/**
* Applet init() method
*/

public void init() {

// get the image
getImageSimple();
// or
// getImageWithMediaTracker();
}

/**
* Applet paint() method
*/

public void paint(Graphics g) {
// draw the image and location
int x = 0;
int y = 0;

// this is refers to image observer
g.drawImage(im, x, y, this);
}

/**
* Simply get the Image
*/

private void getImageSimple() {
// get the image
im = getImage(getDocumentBase(), IMAGE);
}

/**
* Get the Image and add Media Tracker to see image downloading
*/

private void getImageWithMediaTracker() {
// get image
im = getImage(getDocumentBase(), IMAGE);

// create and add Media Tracker
MediaTracker tracker = new MediaTracker(this);
// add the image to tracker and give it an id say 0
tracker.addImage(im, 0);
try {
// start loading the image with Id = 0
// in this case the image
tracker.waitForID(0);
} catch (InterruptedException e) {
System.out.println("Error loading Image : " + e.getMessage());
}
}

}