/**
* How to use MediaTracker to load media first
*/
import java.awt.*;
import java.applet.*;
public class UseMediaTracker extends Applet {
// initialize variables
int appletWidth, appletHeight;
// text ascent and descent
int ascent, descent;
// text width
int stringWidth, x, y;
Image bg, ship1, ship2, plane1, plane2;
MediaTracker tracker;
/**
* (1) overrides Applet init()
*/
public void init() {
appletWidth = this.getSize().width; //get Applet screen width
appletHeight = this.getSize().height; //get Applet Screen height
// initialize image objects
bg = getImage(getCodeBase(), "images/bg.gif");
ship1 = getImage (getCodeBase(), "images/ship1.gif");
ship2 = getImage (getCodeBase(), "images/ship2.gif");
plane1 = getImage (getCodeBase(), "images/plane1.gif");
plane2 = getImage (getCodeBase(), "images/plane2.gif");
//initilize tracker object
tracker = new MediaTracker(this);
//adding images to the tracker
tracker.addImage(bg, 0);
tracker.addImage(ship1, 0);
tracker.addImage(ship2, 0);
tracker.addImage(plane1, 0);
tracker.addImage(plane2, 0);
try {
this.showStatus("Loading...");
tracker.waitForAll();
}
catch(InterruptedException E){};
}
/**
* (2) Paint images
*/
public void paint (Graphics g) {
// if there are some errors happened when loading images
if((tracker.statusAll(false) & MediaTracker.ERRORED) != 0) {
FontMetrics fm = g.getFontMetrics();
ascent =fm.getAscent();
descent = fm.getDescent();
stringWidth = fm.stringWidth("Loading Errors...");
// calculate text center location
x = (appletWidth - stringWidth) / 2;
y = (appletHeight - (ascent + descent)) / 2 + ascent;
this.setBackground(Color.black); //Applet background color
g.setColor(Color.white); //text color
g.drawString("Loading Errors...", x, y); //centered text
return;
}
//if loading is successful, then draw images
g.drawImage(bg, 0, 0, 320, 240, this);
g.drawImage(ship1, 20, 140, 80, 80, this);
g.drawImage(ship2, 180, 140, 80, 80, this);
g.drawImage(plane1, 30, 10, 100, 100, this);
g.drawImage(plane2, 250, 50, 50, 50, this);
}
}
Applet MediaTracker
Saturday, September 16, 2006
I wrote an Applet example that shows how to use Media Tracker class to load all images before drawing them, otherwise it shows an error message.


0 Comments: