I want to be able to load an image from inside the jar.
Many pages say to use the exact code I am using. Some say to use getClass()
, but I am running the code in my main method and my class is not static.
Currently I have the following code in the main method on the main class.
try {
ImageIcon icon = new ImageIcon(BlockWorld.class.getResource("icon.png")); // line 46
window.setIconImage(icon.getImage());
} catch (Exception e) {
e.printStackTrace();
}
I know for a fact that icon.png
is in the root of the jar. It is a 128 x 128 png with no alpha.
Everything compiles fine. When I run the jar, it put out the following.
java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at com.Tgwizman.BlockWorld.BlockWorld.main(BlockWorld.java:46)
Does anyone have any suggestions?
在路径中添加一个斜杠以使用jar的根文件夹。
getResource("/icon.png")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.