I want to upload a picture to a form in a JavaFX application. Now I do it as follows:

ImageView imageView1 = new ImageView("file:/hourglass.jpg"); 

The problem is that the picture is taken directly from the root of the D drive. I also need to set the path relative to my Java program. Construction, type:

 ImageView imageView2 = new ImageView("/img/ilovedogs.jpg"); 

does not work. Writes this:

Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found

How to configure everything and where to create the img folder?

  • img/ilovedogs.jpg or ./img/ilovedogs.jpg or all the same with the addition of file: front file:./img/ilovedogs.jpg - Sergey
  • Thank! It turns out it was necessary to put a dot at the beginning. Of all the above, ImageView imageView2 = new ImageView ("file: ./ img / ilovedogs.jpg") works; - faoxis

1 answer 1

Try this method:

 private static final File ROOT = codeSourceDir(Main.class); private static File codeSourceDir(Class<?> clazz) { try { URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI(); File jarOrDir = new File(uri); return jarOrDir.isDirectory() ? jarOrDir : jarOrDir.getParentFile(); } catch (Exception e) { throw new UnhandledException(e); } }