Java ImageIO.read(getClass().getResource()) returns null

后端 未结 1 1030
礼貌的吻别
礼貌的吻别 2020-12-20 02:46

The line

andImg = ImageIO.read(getClass().getResource(\"gate_and.png\"));

fails with

Exception in thread \"AWT-EventQueue-         


        
相关标签:
1条回答
  • 2020-12-20 03:16

    Assuming your class is in package view.random.name, then

    getClass().getResource("gate_and.png")
    

    will look for the resource in

    /view/random/name/gate_and.png
    

    relative to the root of the classpath. You apparently don't have a resource by that name there.

    By setting project/images as a build path entry, Eclipse will include everything in it on the classpath. Therefore, your resource will appear at

    /gate_and.png
    

    You can access it with

    getClass().getResource("/gate_and.png")
    

    Note the leading / that means start looking at the root of the classpath, ie. it's an absolute path.

    All these rules are explained in the javadoc.

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