DingDongDang132
DingDongDang132

Reputation: 67

I can't load an image in Javafx

I've read many other topics about this in stackoverflow, and yet none of their solutions seem to fit my problem. There are no errors, just a blank stage, and I dont' understand why.

public void titleView(Pane pane)
{
    Image img = new Image("file:test.png");

    ImageView title = new ImageView(img);
    title.setImage(img);
    title.setLayoutX(569);
    title.setLayoutY(146);
    title.fitHeightProperty().add(100);
    title.fitWidthProperty().add(100);
    title.setVisible(true);

    pane.getChildren().add(title);

    System.out.println("success!!!");        
}

This is the method I've made. The "test.png" file is just a red 100x100 picture made in paint. It's located in the project and in a folder I've made: res/textures/test.png I did remember to build path to it

Pane pane = new Pane();
titleView(pane);

I hope somebody can help, thanks

Upvotes: 0

Views: 2712

Answers (3)

SedJ601
SedJ601

Reputation: 13859

I run into this problem a lot. The way I start to solve it is by making sure the file exits. A lot of the time is basically a wrong file path.

Try:

    File file = new File("YourFile.jpg");
    if(file.exists())
    {
        System.out.println("file exist!");//I would print file path here.
    }
    else
    {
        System.out.println("file does not exist!");
    }

If the file does not exits, play with your file path: File file = new File("src/img/YourFile.jpg");

If the file exits one of the other mentioned methods should work.

Upvotes: 0

Fevly Pallar
Fevly Pallar

Reputation: 3099

Try this .getResourceAsStream :

Image image = new Image(getClass().getResourceAsStream("pic.png"));
 title.setImage(image);

getClass().getResource("...") also throws me NPE in Netbeans.

Upvotes: 1

ivanivan
ivanivan

Reputation: 2215

It all has to do iwth your file path references...

Image img = new Image(YourMainClassName.class.getClass().getResource("test.jpg").toString());

Or similar may work

Upvotes: 0

Related Questions