Search code examples
javaimagepathembedded-resource

Can't define a path to an image


I imported an image into Eclipse, in the same package as this class:

public class mainWindow extends JFrame {
    public mainWindow() {
    Image bg = // \mainPackage\ShittyPlane.png;
    Graphics2D g2d;
    this.setSize(500,500);
    this.setResizable(false);
    this.setTitle("GameTest");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setVisible(true);
    g2d.drawImage(bg, 0, 0, null);
  }
}

How do I define the image path?


Solution

  • If the image is part of you source and is packed into jar later for distribution i would sucgest you get a stream to the image using getResourceAsStream.

    ClassLoader cl = getClass().getClassLoader();
    InputStream is = cl.getResourceAsStream("mainPackage/ShittyPlane.png");
    BufferedImage image = ImageIO.read(is);
    

    this aproache will also work in if you run the program from your IDE

    If you plan to locate the image using a a File chooser then go with @Pescis's answer.