简体   繁体   English

图片不会从jar的根加载

[英]Image won't load from root of jar

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. 有人说要使用getClass() ,但是我正在main方法中运行代码,而我的类不是静态的。

Currently I have the following code in the main method on the main class. 目前,我在主类的main方法中具有以下代码。

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. 我知道icon.png位于罐子的根中。 It is a 128 x 128 png with no alpha. 它是没有Alpha的128 x 128 png。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM