简体   繁体   中英

JavaFX ImageView image not showing

I have an assets folder full of images to implement in a game I'm creating and I want to display these in the window. This is my code so far.

public class javafxtest extends Application {
    public void start(Stage primaryStage) throws Exception {
        Group root = new Group();
        Scene scene = new Scene(root, 600, 600);

        Image test = new Image("file:assets/BA.png");
        ImageView piece = new ImageView(test);
        piece.setX(10);
        piece.setY(10);

        Rectangle rct = new Rectangle(50, 150, 500, 300);
        rct.setFill(Color.GRAY);

        root.getChildren().addAll(rct, piece);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

This will be for a program to run within IntelliJ/from a jar. The assets folder is in the same directory as this file. I get no file path error so I assume it can find the image, but it doesn't appear on screen and the rectangle does.

Fair warning, I'm learning JavaFX from scratch and I'm finding there's not much explanation as to how things work, so this could be a stupid question.

Accessing the image via the filesystem is the wrong choice when the image is in fact an asset (ie it is distributed along side the .class files that make up your program) because that way you'd have to deal with the installation path (otherwise known as the home path ). The correct choice is bundling your image in your JAR, so place your image in the following path:

src/main/resources/assets/BA.png

and access it with:

Image test = new Image("/assets/BA.png");

This is how the file tree should look like in your computer:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM