1

I am trying to make a few different jpgs appear on a GUI I am working on. Originally, I was just referencing the file on my computer but I now want to put the jpgs into my project folder and reference them from there. I was looking up how to do this online and I have gotten this far:

        BufferedImage myPicture = null;
    try {
        myPicture = ImageIO.read(getClass().getResource("/HIOLogo.jpg"));
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    JLabel headerImage = new JLabel(new ImageIcon(myPicture));

    headerImage.setBounds(0, 0, 200, 200);
    this.add(headerImage);
}

However, I am not sure where I should be putting the HIOLogo.jpg file within my project? Right now I just dragged the file straight into the project folder. When I run this I get an IllegalArgumentException.

user4305589
  • 43
  • 1
  • 7

1 Answers1

0

Is your file in the root folder?

for example if the file is in src folder the path should be "/src/HIOLogo.jpg"

If it's in folder outside src (root folder) then your path is right

so,

If the path is relative to the root of the classpath (specified by the leading /).

ImageIO.read(getClass().getResource("/path/to/resource"));

else if the path is relative to the root of the classpath (specified by the leading /).

ImageIO.read(new File("path/to/resource");

the path is relative to the root of the classpath (specified by the leading /).

More info here

Community
  • 1
  • 1
Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
  • Originally my file was in the root folder and I was using the getClass().getResource("/HIOLogo.jpg") and that is when I was getting the illegal argument exception. Which I believe based on what you said I had the right path? So I am wondering if I am missing something else. I also tried the new File("/HIOLogo.jpg") and that gave me an IIoexception – user4305589 Nov 29 '14 at 22:46