N30
N30

Reputation: 53

Can't find proper image path

I just googled and searched this site, found a lot of stuff, but either did I not understand the principle or am doing it wrong.

Actually the Class and the Image are not in the same directory, but to ease things for testing, I put the image into the same folder as my class.

These are the two lines:

ImageIcon img = new ImageIcon("gimmick_facepalm.png");

System.out.println(img.getIconWidth() + " " + img.getIconHeight());

Output is always -1 -1, so I suspect that Java does not read in the image.

Hint or solution would be appreciated :)

Thanks!

Upvotes: 0

Views: 766

Answers (2)

Syam S
Syam S

Reputation: 8499

Try

URL url = ClassLoader.getSystemResource("gimmick_facepalm.png");
ImageIcon img = new ImageIcon(url);

System.out.println(img.getIconWidth() + " " + img.getIconHeight());

Upvotes: 0

schmop
schmop

Reputation: 1440

If you do not specify an absolute path (ie. C:/... under windows), the current directory will be the directory where the program was executed, not the class folder (your project root in eclipse for instance, or where your were when you invoked the "java" command).

Furthermore, you can access files in a package of the classpath like so:

File file = new File(ClassLoader.getSystemResource("name/of/package/"+fileName).toURI());

Or directly with ImageIcon:

new ImageIcon(ClassLoader.getSystemResource("name/of/package/"+fileName));

Upvotes: 2

Related Questions