0

My current project, when run in Eclipse, has no errors. However, after exporting to a runnable jar, it doesn't function at all. Running from command prompt produces the following error message:

Uncaught error fetching image:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(Unknown Source)
    at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
    at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
    at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
    at sun.awt.image.ImageFetcher.run(Unknown Source)

Testing has brought me to the conclusion that the error occurs when I try to load images required for the project, with lines similar to the following:

grassTile1 = rl.getImage("\\grassTile1.png");

rl is an instance of ResourceLoader, for which getImage is the following:

public Image getImage(String x){
    URL y = this.getClass().getResource(x);
    System.out.println(y);
    Image img = tk.getImage(y);
    if(img==null) throw new IllegalArgumentException("Image at "+x+" not found.");
    System.out.println(y);
    return new ImageIcon(img).getImage();
}

tk is obtained via Toolkit.getDefaultToolkit();. The images exist in the same directory as ResourceLoader.class within the jar. Commenting out the call to loadImages(), which contains the only calls present to ResourceLoader, causes the program to run, though obviously without image resources.

The program runs as expected within Eclipse. What changes should be made to the relative paths referenced so that they will function properly when compiled to a jar?

EDIT: Changes to ResourceLoader.getImage() based on feedback.

public Image getImage(String x){
    URL y = this.getClass().getResource(x);
    System.out.println(y);
    ImageIcon icon = new ImageIcon(getClass().getResource(x));
    Image i = icon.getImage();
    return i;
}

Is this better or worse than the original getImage() function I wrote?

UPDATE TWO: Removing the leading slashes from the data passed into getImage() fixed the problem, as suggested by Perception.

Passage
  • 234
  • 3
  • 12

0 Answers0