0

I need to display an image in a JPanel, but this image needs to be in a relative folder (my res folder) in my project path, so that my program can work on any machine, and the images are always available. The code I have for this so far is:

try {
            BufferedImage image = ImageIO.read(new File("res/circle.jpg"));

            JLabel picLabel = new JLabel(new ImageIcon(image));

            panel2.add(picLabel);

            picLabel.setLocation(220, 180);
            picLabel.setSize(100, 100);

        } catch (IOException e1) {
            e1.printStackTrace();
        } 

This code is reading the error "Can't read input file!" and I cant figure out what I'm doing wrong.

(my res folder is located in the src folder of the project)

FLOX DAW
  • 1
  • 3
  • It's also possible that the image isn't a valid jpeg format for ImageIO – MadProgrammer Jun 04 '16 at 08:11
  • *"my res folder is located in the src folder of the project"* - Well, like or the other questions on this subject, you need to use `Class#getResource` instead of `File` – MadProgrammer Jun 04 '16 at 08:15
  • The res folder is located in the same folder as the main.java – FLOX DAW Jun 04 '16 at 08:35
  • It doesn't change the answer, you need to use Class#getResource instead of File to load the resource – MadProgrammer Jun 04 '16 at 08:58
  • After trying all answers I figured out that I needed to move the res folder up a directory so that it was in the same directory as the src folder and the classpath files. This has solved the problem and works with my original code – FLOX DAW Jun 04 '16 at 09:01
  • Until the "working" directory is no longer the same directory that contains the `res` directory. `getClass().getResource("res/circle.jpg")` is a more reliable solution (assuming the class loading the resource is in the same package as the `res` directory) or you can use an absolute path, something like `getClass().getResource("/{package name}/res/circle.jpg")` – MadProgrammer Jun 04 '16 at 09:25

2 Answers2

0

Let's take an example. Here is a small directory structure

main
   |---MyClass.java
   |---myfile.png

So main is package. You will need a class to reference any resource. Here I am using MyClass.

public Image getImage() throws IOException{
    return ImageIO.read(MyClass.class.getResource("myfile.png"));
}
afzalex
  • 8,598
  • 2
  • 34
  • 61
0

You can use something called get current directory. This will get the folder path that the project is working off of.

You can use it like so: System.getProperty("user.dir")

Just add the image to the correct folder and then add the path and you're golden.

ALegendsTale
  • 41
  • 3
  • 8
  • *"my res folder is located in the src folder of the project"* would suggest that the images are embedded within the jar, not in the current dir. `user.dir` also returns the current "working" directory, which may be different from the directory where the program is stored – MadProgrammer Jun 04 '16 at 08:26