-2

I try to display image for my game project in Java, using Eclipse IDE: I have the ImageReader:

public BufferedImage loadImage(String path) {
    try {
        BufferedImage image = ImageIO.read(getClass().getResource(path));
        return image;
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    return null;
}

I load the image from the GameWindow class:

@Override
public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2D = (Graphics2D) g;

    g2D.drawImage(ImageReader.getInstance().loadImage("/x.png"), 0, 0, Game.FIELD_HEIGHT, Game.FIELD_WIDTH, null);
}

This is my Package Explorer: Package Explorer

When I try to run the program I receive the following error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at game.util.ImageReader.loadImage(ImageReader.java:31)
at game.util.ImageReader.<init>(ImageReader.java:18)
at game.util.ImageReader.getInstance(ImageReader.java:24)
at game.gui.GameWindow.paint(GameWindow.java:31)

Thanks to any help!

1 Answers1

0

You may have to change the image read code as

public BufferedImage loadImage(String path) {
try {
    BufferedImage image = ImageIO.read( new FileInputStream( new File( path ) ) );
    return image;
} catch(IOException e) {
    e.printStackTrace();
    System.exit(-1);
}
return null;
}

I assume for filepath is correct and your res directory is marked as the resource directory properly.

Klaus
  • 1,641
  • 1
  • 10
  • 22
  • How can I know if my filepath is correct and the res directory is marked as the resource directory properly? I tried your solution, but unfortunately, I received the following error: java.io.FileNotFoundException: \0.png (The system cannot find the file specified) – Tomer Zager Apr 14 '20 at 14:24
  • Why it is like 0.png? Shouldn't it be x.png?? Also, i assume you have not setup the resource root properly. Try with the absolute file path instead of the relative file path. Ex : C://user/images/x.png Try https://stackoverflow.com/questions/36907204/how-to-create-a-src-main-resources-directory and setup the resource dir properly – Klaus Apr 14 '20 at 19:12