0
    theDeck.setIcon(new ImageIcon(getClass().getResource("/Cards-1.png")));

Above is code that i set an icon of a jlabel. The program structure is shown here

My question is when I try to run the program using command line, it will give me a nullpointer exception. But if i run the same problem using intellij IDE or gradle, it works fine. What is the reason here?

This is the exception that it throws

   System.out.println(getClass().getResource("/").getPath());

I tried to figure out the root directory of the image when running gradle, and it shows me it is in (something)/build/classes/java/main/. I think my main question is why changing the classpath will solve the problem? My image is not in the path, how does the program find the image?

Nat
  • 50
  • 7
  • So what's null? Is `getClass().getResource(...)` returning null, or is that throwing? You've got a *lot* going on for a single line of code that's throwing - separate it into tiny stages. – Jon Skeet Oct 24 '17 at 16:02
  • Do you run the whole JAR or just a class? Also, it is usually better to use some ClassLoader that is not tied to the current class, the java resources are a bit mind-bending and I guess it's easier to just centralize the resource management for the project. – Vlasec Oct 24 '17 at 16:04
  • I updated the exception I got when running only the class. I think it's becuase the getResource cannot get the image, so it returns null. The imageicon didn't receive any source so it throws nullerpointer exception. That's doesn't seem to happen when I try with gradle build and gradle run. – Nat Oct 25 '17 at 00:36

0 Answers0