sahar
sahar

Reputation: 569

get path of image file that is outside the project in java

I use this code to display image that locates outside the my java project, but I got NullPointerException every time and I can only use images that are inside my project directory. why ?

Icon welcomeImg = new ImageIcon(getClass().getResource("D:/img/welcome.png"));
or 
Icon welcomeImg = new ImageIcon(getClass().getResource("D://img/welcome.png"));

JLabel welcomingLb = new JLabel(welcomeImg);

Upvotes: 0

Views: 1705

Answers (4)

Jean Logeart
Jean Logeart

Reputation: 53819

You do not need to use the ClassLoader class to access your file since you are giving its full path.

Try instead :

Icon welcomeImg = new ImageIcon("D:/img/welcome.png");

Source : Javadoc of ImageIcon(String filename)

Upvotes: 2

DaveJohnston
DaveJohnston

Reputation: 10151

See: Loading resources using getClass().getResource()

Basically when you use getResource it is expecting the file to be on the Classpath. There is also a constructor for ImageIcon that takes a String filename, so you can pass the path to the Icon file directly.

Check out the JavaDoc for ImageIcon

Upvotes: 1

f1dave
f1dave

Reputation: 1297

You can try using a File, like so:

File f = new File("C:\\folder\\stuff\\MyFile.class");

Upvotes: -1

Dave Newton
Dave Newton

Reputation: 160191

getResource expects the resource to be on the classpath.

If you want to read from a random file, use a File, or use the ImageIcon constructor that takes a file name.

Upvotes: 2

Related Questions