0

When I try to make an image for some reason my path does not work and I have no idea why. Do I have to use ImageView instead?

Image planetPicture = new Image("/Users/rizins/Desktop/earth.gif");

I get the error

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

at javafx.scene.image.Image.validateUrl(Image.java:1089)

Any ideas on how to fix this would be much appreciated, or a link to another post.

RIZY101
  • 29
  • 6

2 Answers2

0

It is how you are referencing the image. Which also kinda depends on if you are using an IDE, etc. This is what works for me in Netbeans...

If your directory structure looks like

src/
├── yourclass
│   ├── YourClass.java
└── images
    ├── Image-1.png
    ├── Image-2.png

Then something like

Image myImage=new Image(YourClass.class.getClass().getResource("/images/Image-1.png").toString());
ImageView imgView=new ImageView();
imgView.setImage(myImage);

Should work for you....

ivanivan
  • 2,155
  • 2
  • 10
  • 11
  • The last two lines can be written as `ImageView imgView = new ImageView(myImage);`. – VGR Jan 24 '17 at 19:46
  • Indeed. But I was copy/pasting from some homework I did last term, it was easier to change my references from an array to a straight up object instead of merging the lines together... – ivanivan Jan 24 '17 at 19:51
  • So I wanted to let you know that this did work form but I was implementing a sprite class that had to use an image variable not imageView because it uses the graphicsContext and canvas libraries but this worked as well for file structure of other projects so thank you – RIZY101 Jan 25 '17 at 02:03
0

Well the image constructor expects an URL and you don't provide the protocol so you need to pass "file:/Users/rizins/Desktop/earth.gif"

tomsontom
  • 5,856
  • 2
  • 23
  • 21
  • That will work in this case, but in the general case, simply prepending "file:" to a file name is *not* sufficient, as not all characters which are valid in file names are valid in URLs. (I’m not criticizing you, I’m mentioning it because I have seen that exact mistake made more times than I can count, including in a lot of Stack Overflow posts.) – VGR Jan 24 '17 at 20:40
  • Wow I cant believe I forgot to do that...but thank you again this is exactly what I was looking for! – RIZY101 Jan 25 '17 at 02:04