UPDATE: both methods currently work in the AppletViewer but not Internet Exploder
I am having a heck of a time loading images in my applet. Since the project has just begun, I’m launching from a directory on my computer. Using JRE version 1.4.2 Java HotSpot™ Client VM, No proxy.
The first problem I noticed is that Applet.getDocumentBase() is returning the wrong thing. It’s supposed to return a URL to the directory that the HTML page lives in, but no, it returns a URL to the HTML page itself. Fine, I’ll cull the real base out of the URL. I put together a real document base URL and try Applet.getImage().
It never worked. I draw the image and there’s just nothing there. I switched my code around to use a MediaTracker ala nonnus29’s game tutorial ( thanks! ) but now I just know that I have errors. I’m really stuck on this one. How do I find out what the error was? Why is my documentBase screwed up?
Perhaps even more interesting is what happens when I load the image from the jar. Using my old fade-in Splash Screen code I got some weird results. It opens the image and “reads” it without error, but the image loaded is mostly screwed up. You can tell it came from my image file, but more than half of it looks like stretched out pixels. But it fades in nicely! Sure glad to see my rendering loop and bufferstrategy work cause not much else is.
this always prints “Error loading Image”
URL docBase = getDocumentBase();
String docPath = docBase.toString();
if ( !docPath.endsWith("/") ) {
// java gave us the file name, not the actual base
// maybe this only happens with files
int pos = docPath.lastIndexOf('/');
docPath = docPath.substring(0, pos );
}
URL realDocBase = null;
try {
realDocBase = new URL( docPath );
} catch (MalformedURLException mfux ) {
mfux.printStackTrace();
throw new RuntimeException( "cannot open images" );
}
System.out.println( realDocBase );
MediaTracker t = new MediaTracker (this);
image = getImage(realDocBase,getParameter("splash_image" ));
t.addImage(image,0);
try {
t.waitForAll();
}
catch (InterruptedException e) {}
if (t.isErrorAny()) {
System.out.println("Error loading Image");
}
And this loads a broken image from the jar
private void loadImage() {
BufferedImage background = null;
URL imageURL = getClass().getClassLoader().getResource( "logo2.jpg");
try {
background = ImageIO.read( imageURL );
} catch ( IOException e ) {
System.err.println( "couldn't load image" );
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
compatible = graphicsConfig
.createCompatibleImage(background.getWidth(), background.getHeight(),
Transparency.BITMASK);
backBuffer = graphicsConfig
.createCompatibleImage(background.getWidth(), background.getHeight(),
Transparency.BITMASK);
Graphics g = null;
try {
g = compatible.getGraphics();
g.drawImage(background, 0, 0, null);
} finally {
if (g != null)
g.dispose();
}
background = null;
}
Thanks!