Java getClass().getResource(“file”) leads to NullPointerException

后端 未结 11 1124
[愿得一人]
[愿得一人] 2020-12-11 01:18

I am following the zetcode Snake java games tutorial and always get this error:

ImageIcon iid = new ImageIcon(this.getClass().getResource(\"ball.png\"));
bal         


        
相关标签:
11条回答
  • 2020-12-11 01:49

    Try this:

    ImageIcon iid = new ImageIcon(this.getClass()
                      .getClassLoader().getResource("ball.png"));
    ball = iid.getImage();
    

    Make sure image is in the same folder as java file.

    0 讨论(0)
  • 2020-12-11 01:54

    if the resource is in your classpath then you should be trying "this.getClass().getClassLoader().getResource("ball.png")". For you actual code to work, the ball.png needs to be in the location where your .class file is (i.e., inside the package).

    0 讨论(0)
  • 2020-12-11 01:58

    I will make it simple for you . Here is an example:

    Icon bug = new ImageIcon(getClass().getResource("bug1.png"));
    

    here "bug1.png" is the resource and if it is unavailable then it can cause error as you have discussed here.

    Import an image to the same directory in which your program resides.

    You can also give whole path to it as well

    ImageIcon(getClass().getResource("C://me/file/bug1.png"));
    
    0 讨论(0)
  • 2020-12-11 01:59

    It is general risky to load resources using relative paths, I'd always recommend using absolute paths, so do

     /ball.png
    

    if the the image is at the root of your classpath, or add a path to the location.

    0 讨论(0)
  • 2020-12-11 02:03

    Try using System.out.println(System.getProperty("java.class.path")); to find out location of your .class file and place the images in this folder.

    0 讨论(0)
提交回复
热议问题