Question

I made an application that uses an image as the background to an image, when i run it in eclipse it works perfectly, but when i pack it into a .Jar file the image is not showing. i surfed Stackoverflow for Answers i found similar posts and i tried the solutions but nothing worked.

here is what i ended up doing.

private void init(){
setPreferredSize( new Dimension( w, h ) );
setVisible(true);

URL url = getClass().getResource("Graph2.png");
System.out.println("Value = " + url);
img = Toolkit.getDefaultToolkit().createImage(url);
}

the constructor calls this function to initialize the GUI then i call this function in the paintcomponent to draw the image

private void initializeGrid(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(img, 0, 0, this);

}

not sure what is the problem i tried putting the image everywhere, from a folder outside the src to inside the bin to inside the GUI package in the bin nothing worked.

thanks in advance

Was it helpful?

Solution

The typical way to set this up is to create your folders like this in Eclipse:

bin/
resources/
src/

Create your package structure in resources exactly like it is in src and bin. Copy your image file to the same package in resources as the class that will try to load it in src.

In Project > Properties > Java Build Path > Source, add both src and resources as source folders. Now when you build the project the contents of resources will be copied over to bin and it will work from your IDE as well as from a JAR.

OTHER TIPS

Please try to specify absolute location to you image in JAR, like

URL url = getClass().getResource("/com/test/mypackage/Graph2.png");

if your image place near of your class or

URL url = getClass().getResource("/Graph2.png");

if your image place in root of JAR file

Also please note about case of file name "Graph2.png" is not "graph2.png"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top