user9152856
user9152856

Reputation: 109

right way to make a jar file from javafx application

I have a javafx project, which contains multiple paths for images and text files :

private Image imgMan = new Image(getClass().getResource("../man.gif").toExternalForm());

FileHelper.resetScores("./bin/application/MAP/BestScores.txt");

...

When i launch from eclipse, it work normally, and access to images and files without any problem.

But when i try to export my project to a jar file, it export correctly, but it don't launch !

I try to launch it from cmd, the trace of stack said that he don't know the paths...

Caused by: java.lang.NullPointerException at application.Client.(Client.java:31)

(line 31 in my code refer to the first line of code given in the question)

I try to create a resource folder and put all files into it, but no result.

So what is the best way to make it ? where must i create the resource folder ? and how to access the files into it from the code ?

Thank you

Upvotes: 0

Views: 879

Answers (1)

NoDataFound
NoDataFound

Reputation: 11959

There are several thing you should check:

  • verify the path in your jar against the class you are looking. Your image must be there.
  • verify you have successfully loaded a resource because using it, eg: check if getResource returns null.

For the first point, it depends on how you build your jar:

  • Eclipse will by default copy class file and resources to bin unless you use m2e. If you use the Extract runnable JAR (from File > Export menu), it may ignore some resources.
  • If you use Maven then your images must be in src/main/resources by default.

For the second point, you should use a method that should check the resource exists before delegating to Image. While it won't change your core problem, you would have a less subtile error:

static javafx.scene.image.Image loadImage(Class<?> source, String path) {
  final InputStream is = source.getResourceAsStream(path);
  if (null == is) {
    throw new IllegalStateException("Could not load image from " + source + " path: " + path);
  }
  try (is) { // Java 9 -> you may want to use InputStream is2 = is
    return new javafx.scene.image.Image(is); // use is2 for Java < 9
  }
}

You should also try with an absolute path (from the root of the jar, or your src/main/resources if you use maven):

Image image = loadImage(this.getClass(), "/images/man.gif");

Upvotes: 1

Related Questions