Nabuska
Nabuska

Reputation: 463

JavaFX Creating an Image and ImageView

Stuck in the basics. I have some syntax issues setting up the Image Path. When i try to create an Image and give it the image path, it always throws some some exception about the path. I have commented out some of the path combination I have already tryed. Can you please tell me what I am doing wrong? Thank you.

package jopofx;

public JoPoCTRL(JoPoFX gui){
    this.gui = gui;  
}

public void updateImages(){
    Image img = null;
    try{
        //img = new Image("C:\\Users\\ ... //FullPath ... \\JoPoFX\\src\\jopofx\\myimage.png");
        img = new Image("\\JoPoFX\\src\\jopofx\\myimage.png");
        //img = new Image("\\src\\jopofx\\myimage.png");
        //img = new Image("\\myimage.png");

    }catch(Exception e){
        System.out.println("error while creating image");
        e.printStackTrace();
    }

    try{
        gui.setImgV(img);
    }catch(Exception e){
        System.out.println("error while setting up the image");
    }        
}

This is what prints out: error while creating image java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found at javafx.scene.image.Image.validateUrl(Image.java:990) at javafx.scene.image.Image.(Image.java:538)

Upvotes: 1

Views: 6837

Answers (2)

Nabuska
Nabuska

Reputation: 463

I found a working example from a blog short after I posted my question. Hopefully this example will be helpful to someone:

InputStream stream = getClass().getResourceAsStream("images/"+imageName+".jpg");
//"images/" is the a local directory where all my images are located
Image newImage = new Image(stream); 
imgV.setImage(newImage);

Upvotes: 0

ItachiUchiha
ItachiUchiha

Reputation: 36722

On Windows platform, for an image placed inside src/jopofx :

img = new Image("\\jopofx\\myimage.png");

or

img = new Image("/jopofx/myimage.png");

Then you can create an ImageView using:

ImageView imageView = new ImageView(img);

Further, you can also directly initialize an ImageView without initializing an Image by:

ImageView imageView = new ImageView("/jopofx/myimage.png");

Also, make sure you are using the import javafx.scene.image.Image;

Upvotes: 2

Related Questions