2

I have a Java/JavaFX project where I use style sheets.

Images from stylesheets will get loaded as follows:

#pane {
-fx-background-image:url('../packagename/image.jpg');
 }

It loads fine when I compile and run it from Eclipse or Scenebuilder. However, when running my jar file from the cmd (java -jar project.jar), it adds the file name to the path, changing it to:

project.jar/packagename/image.jpg

and obviously failing to load it. How do I get the correct path, or alternatively, omit the jar from the somehow jar generated path? The jar file is in the package folder here outlined as packagename.

sandboxj
  • 1,234
  • 3
  • 21
  • 47
  • 1
    Is the image added to the jar file (check, if it's listed by `jar tf project.jar`)? Do the urls meet the requirements specified in the css reference ( https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#typeurl )? – fabian Dec 19 '16 at 22:04

2 Answers2

0

Add all of the images to a source folder. Since you said you're using Eclipse, just right click on your project -> New Source Folder. Name it something like res. Copy and paste all of your images in there.

ack
  • 1,181
  • 1
  • 17
  • 36
  • How does this help? I still have to put in the path in the css file which then gets changed again by the jar file or? – sandboxj Dec 19 '16 at 21:42
  • @sandboxj You would just put in "image.jpg", not the whole path. – ack Dec 19 '16 at 21:43
  • I tried both suggestions. The problem remains when running the .jar file. I am using the Export -> Java - > JAR file option. And I selected Export generated class files and resources and Export Java source files and resources – sandboxj Dec 19 '16 at 21:49
  • Do I have to move the project.css file in the source folder too? Because if I move the pictures only it does not work at all, not even in eclipse. – sandboxj Dec 19 '16 at 21:57
  • Yes. Move it in the `res` folder. – ack Dec 19 '16 at 21:58
0

Assuming the "packageName" is a path from the root of the jar file, it will obviously fail. The ../ prefix on your path will cause your relative location will go up to its parent directory, and search the part after the ../ from that directory.

In eclipse the parent directory would propably be the project directory, while in your .jar file, it is the jar file itself giving the result you described. A fix would be to use source directories (configured in the "buildpath" in eclipse). The structure of these sourcepath's is up to you, though a common structure is as follows:

Root (either the eclipse project folder, or the .jar file
   | src
   |   | main
   |      | java // usually here goes all the code
   |      | resources  // and here goes all the resources the code needs.

Again the above is no requirement to make a java project perfect, though it is common practise.

Propably another fix would be to use no ../ at all, although Im not sure about that. It might be a .jar-file-only fix.

n247s
  • 1,898
  • 1
  • 12
  • 30