简体   繁体   中英

Image won't load

i am trying to load an image using this methods. I am asking for my image here:

private BufferedImage image = controller.loadImage("/paddle.png");

And the loadImage method is

public BufferedImage loadImage(String path) {
    BufferedImage image = null;
    try {
        image = ImageIO.read(getClass().getResource(path));
    } catch (Exception e) {

        e.printStackTrace();
    }
    return image;
}

I added "res" to my class folder also but nothing seems to work. My project explorer looks like this : http://prntscr.com/hmar35 EDIT: I also tried URL loading but failed to work either,the code for URL loading is:

 public BufferedImage loadImage(String path) {
     BufferedImage image = null;
     try {
         URL link = Controller.class.getResource(path);
         image = (BufferedImage) Toolkit.getDefaultToolkit().getImage(link);
    } catch (Exception e) {

        e.printStackTrace();
    }
    return image;
}

Try using

ImageIO.read(getClass().getClassLoader().getResourceAsStream(path));

where path = "paddle.png" in your case.

If your res folder is set as a source folder, and "paddle.png" is located directly inside of the res folder, you do not need to add a "/" to the file path.

Note: Also make sure you refresh your project to make sure all files are recognized.

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