1

I'm trying to generate a runnable jar file of my project which has a JavaFx gui. The project runs greate in eclipse but whenI try to run the jar:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   ...Caused by: java.lang.NullPointerException: Input stream must not be null

The code for the images looks like:

private Image image1 = new Image(this.getClass().getResourceAsStream("../pic/classic/image1.png"));

What do I need to change so that i can run my jar file with no exception.

Thanks for the help.

fabian
  • 80,457
  • 12
  • 86
  • 114
Chill3er
  • 11
  • 1
  • 3
  • 2
    Do not use `..` in the String. If there is a class in the parent package, use that as a reference for the resource: `SomeClassInParentPackage.class.getResourceAsStream("pic/classic/image1.png")` Otherwise, just refer to the resource with a root-relative resource path: `"/com/example/app/pic/classic/image1.png"` – VGR Jul 18 '16 at 19:55
  • http://stackoverflow.com/a/16122215/5969411 – ManoDestra Jul 18 '16 at 21:35
  • 1
    *"EDIT: Thanks for the help on the first question. another question how can I ..."* No, you got your answer to the question. Do not edit your question to add more questions. I rolled back that edit for this reason. You can still find your content here: http://stackoverflow.com/posts/38444852/revisions . Please ask a new question. Also if the answer works for you, consider accepting it. – fabian Jul 19 '16 at 11:16

2 Answers2

7

The .. is not valid in specifying a resource name in a jar file. According to the documentation on resource naming each component of the resource path should be a valid Java identifier: .. is not.

To fix this, just specify the absolute resource name, relative to the classpath. So if the class you are in is in a package called com.mycompany.myapplication.view, you would use

private Image image1 = 
    new Image(this.getClass().getResourceAsStream("/com/mycompany/myapplication/pic/classic/image1.png"));
James_D
  • 201,275
  • 16
  • 291
  • 322
1

Keep in mind, that image file names are CASE SENSITIVE within jar and are not in IDE (e.g. Eclipse).

So if you have "/resource/image.jpg" argument and IMAGE.jpg filename, application will work in Eclipse and, being exported to jar, will produce NullPointerException in

Image image1 = new Image(getClass().getResourceAsStream("/resource/image.jpg"));
schrodingerscatcuriosity
  • 1,780
  • 1
  • 16
  • 31