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

后端 未结 11 1123
[愿得一人]
[愿得一人] 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:38

    The resource so named wasn't found. It needs to be in the same directory as the .class file you are calling it from. See the Javadoc.

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

    You may need to add the file to your build resources, something like this:

    <build>
        <resources>
            <resource>
                <directory>path\to\resources</directory>
                <includes>
                    <include>ball.png</include>
                </includes>
            </resource>
        </resources>
    

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

    You have to put the image file(ball.png) into your classpath. More details, please take a look at the Javadoc.

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

    Go to project >clean in the eclipse it would refresh the package explorer and you won't face this problem anymore.

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

    You can use only path of your image. I think this will help you: Use this:

    ImageIcon iid = new ImageIcon("C:\\Users\\ranig\\My\\spaceinvaders\\ball.png");
    

    Note: C:\\Users\\ranig\\My\\spaceinvaders\\ball.png is the whole path of ball.png image.

    instead of this:

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

    Note: If u want to only try snake code and only want to get output.

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

    The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class and .png in the same folder. If not, you can use classpath-relative paths in getResource(..), by starting with /

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