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
  • 563
  • 7
  • 16
  • 28
  • `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
  • 156,572
  • 25
  • 250
  • 300
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
  • 50,693
  • 11
  • 81
  • 116
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
  • 9,885
  • 10
  • 52
  • 82
-1

You can try using a File, like so:

File f = new File("C:\\folder\\stuff\\MyFile.class");
f1dave
  • 1,207
  • 3
  • 20
  • 30