Netbeans & Java - using getResource() - returning null

本小妞迷上赌 提交于 2019-12-13 06:08:17

问题


I am trying to load a background to my JFrame using the following code:

image = ImageIO.read(getClass().getResourceAsStream(s));

where for s I have tried:

/res/Background/bg_menu.gif
Background/bg_menu.gif
/Background/bg_menu.gif
res/Background/bg_menu.gif

My res folder is in the project root like so:

Game
-- src
-- res

I have done the following:

Project Properties -> Sources -> Add Folder -> res

The error I'm getting returned is:

java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1348)
at com.game.rpg.tilemap.Background.<init>(Background.java:29)
at com.game.rpg.gamestate.MenuState.<init>(MenuState.java:34)

回答1:


If this is your package structure

/res/Background/bg_menu.gif

and /res is a source folder, then

/Background/bg_menu.gif

should be at the root of your classpath. As such, you can access it with

image = ImageIO.read(getClass().getResourceAsStream("/Background/bg_menu.gif"));

Note the leading /. The rules for the path are explained in the javadoc.

If this doesn't work, then your application is not being built correctly with Netbeans. check the deployment.



来源:https://stackoverflow.com/questions/19161395/netbeans-java-using-getresource-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!