0

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);
sahar
  • 569
  • 7
  • 16
  • 29
  • `welcome.png` sounds like an application resource, possibly a splash-screen. Is it either? If so, the advice to use `File` objects is not the way to go. See [this answer](http://stackoverflow.com/a/8462092/418556) for more details. – Andrew Thompson Dec 22 '11 at 00:40

4 Answers4

2

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

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)

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
1

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

Community
  • 1
  • 1
DaveJohnston
  • 10,031
  • 10
  • 54
  • 83
-1

You can try using a File, like so:

File f = new File("C:\\folder\\stuff\\MyFile.class");
f1dave
  • 1,267
  • 4
  • 20
  • 31