Java image path on netbeans

隐身守侯 提交于 2020-01-30 08:08:33

问题


Im adventuring at Java so Im building a minesweeper. The mechanics are done now I want to make it some user friendly.

Tried to add an ImageIcon to a button on everyway but I cant do it! I dont know how Java works on this!

Im doing this:

(suppose this is extending a JButton)

super(new ImageIcon("/minesweeper/resources/bomb.png"));

I have packages like this:

  • minesweeper
  • minesweeper.components
  • minesweeper.resources (trying to organize images here)
  • test (some stuff for testing only)

Am I doing it wrong? (ofc, but how is it right?)


回答1:


You can get the images in this way:

new ImageIcon(getClass().getResource("/minesweeper/resources/bomb.png"))

Check the Java Doc for public URL getResource(String name)




回答2:


To avoid any problems that may arise, especially when different packaging methods are used, make a new package called res or something, then dunk a Res.java in it. Put your images in the same package directory. Now, when you want to read something, you'll get the InputStream using Res.getClass().getResourceAsStream("filename");, then create a new ImageIcon with the stream (new ImageIcon(is)). This gives you an ImageIcon which you can use with the label.

If you want to use the super constructor for setting the image, you can do it in one go:

super(new ImageIcon(Res.getClass().getResourceAsStream("filename")));

Otherwise, just use setIcon(..);.

Edit: you'll use your existing resources package. Just put a Res.java in there.



来源:https://stackoverflow.com/questions/7655607/java-image-path-on-netbeans

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