编程语言
首页 > 编程语言> > java – Jar将图像作为资源

java – Jar将图像作为资源

作者:互联网

我正试图从我的罐子里加载一个图像.但无论我为getResource()提供什么字符串,它总是返回null.

try {
    System.out.println(Bootstrapper.class.getResource("./img/logo.png").toURI().getPath());
} catch (URISyntaxException ex) {
    Logger.getLogger(CrawlerFrame.class.getName()).log(Level.SEVERE, null, ex);


   }
   ImageIcon ii = new ImageIcon(Bootstrapper.class.getResource("./img/logo.png"));
   setIconImage(ii.getImage());

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at net.sharpcode.crawler.ui.CrawlerFrame.init(CrawlerFrame.java:35)
at net.sharpcode.crawler.ui.CrawlerFrame.(CrawlerFrame.java:28)
at net.sharpcode.crawler.Bootstrapper$1.run(Bootstrapper.java:55)

我试过了:

getResource("") 
getResource(".") 
getResource("./") 
getResource("/img/logo.png") 
Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath()

解决方法:

this.getClass().getResource("/net/sharpcode/crawler/img/logo.png")

标签:java,jar,resources,embedded-resource
来源: https://codeday.me/bug/20190929/1833234.html