I've made an simple applet which loads an image which is included in the .jar-file that I've made. The project has one package named "kap12" and one class named "U1". I have one folder included named "resrc" where my image is located. This folder is located in the root (same folder as kap12).
This is the directory structure:
test.jar
*kap12
-U1.class
*resrc
-django.jpg
test.html //outside the .jar, same folder as where test.jar is located
This program works fine when I run it in Eclipse with Appletviewer (without the .jar). It locates the image and shows it. But when I run it in html with the .jar then the program can't find it. I get nullpointer exception everytime. Here's my .html:
<HTML>
<HEAD>
</HEAD>
<TITLE> U1 </TITLE>
<BODY BGCOLOR="EEEEEE">
<CENTER>
<P ALIGN=CENTER>
<APPLET code="kap12/U1.class"
archive="test.jar"
width="1280"
height="720">
</APPLET>
</P>
</CENTER>
</BODY>
</HTML>
And here's my SSCCE:
package kap12;
import java.awt.FlowLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
public class U1 extends JApplet {
JLabel lbl0;
JLabel img0;
URL imgURL;
ImageIcon django = createImageIcon("resrc/django.jpg");
public void init() {
setLayout(new FlowLayout());
lbl0 = new JLabel("Test");
img0 = new JLabel(django);
getContentPane().add(img0);
getContentPane().add(lbl0);
img0.setVisible(true);
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = U1.class.getClassLoader().getResource(path);
if (imgURL != null) {
System.out.println(""+imgURL);
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
I've tested using getClass() and getClass().getClassLoader(). I've tested writing "/resrc/django.jpg" in the String path. I've tested with and without .jar. I've tested adding the resrc-folder into the kap12 package folder. It seems that I've tested everything. I've spent days trying to get this to work.
What should I write? I've read a lot of threads about this here on StackOverflow but no success. Thanks.
Update: I've tested everything you've written Andrew but it can't find it anyway.
This is what I've got from the -tvf:
C:\Program\Java\jdk1.7.0_40\bin>jar -tvf D:\Path\test.jar 25 Mon Jan 20 14:48:14 CET 2014 META-INF/MANIFEST.MF 2035 Mon Jan 20 14:48:04 CET 2014 pkg/U1.class 496057 Sun Feb 03 15:25:06 CET 2013 resrc/django.jpg