Add images to jar

前端 未结 8 1437
孤独总比滥情好
孤独总比滥情好 2021-02-06 12:30

I want to set icon to my JFrame. I do the following:

Image icon = Toolkit.getDefaultToolkit().getImage(\"src/images/icon.jpg\");
this.setIconImage(icon);
         


        
8条回答
  •  梦毁少年i
    2021-02-06 12:36

    Looking at the source code of URLImageSource, it appears that the reason that getConnection throws an NPE is that it has a null for the url. And that leads me to suspect that

    getClass().getResource("/src/images/icon.jpg")
    

    is returning null. It would do that if it could not locate a resource with that pathname.

    I bet that the problem is that you've got the path wrong.

    To prove / disprove this, you should run jar tvf on the JAR file, and look for the line that matches "icon.jpg". Is the corresponding pathname the same as what you are using? If not, use the pathname from the matching line in the getResource call and it should work. Alternatively, if the file doesn't show up at all, look at the NetBeans build configs that tell it what to put in the JAR file. (I'm not a NetBeans user, so I can't say where you would need to look ...)


    If that leads you absolutely nowhere, another possibility is that getClass().getResource(...) is using a classloader that doesn't know about the JAR file containing the image. (This seems pretty improbable to me ...)

提交回复
热议问题