问题
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