简体   繁体   中英

Image not loading from jar

I made an application in which I had some images to be loaded for icons. The program runs fine with every thing working and images loading as expected , when I was loading the images using

imageOpen = Toolkit.getDefaultToolkit().getImage("Images\\open.png");

But when I exporter it as jar the Images didn't show up Then after looking here and there I tried some things but in both cases the URL is returning null

URL u = this.getClass().getResource("Images\\open.png");
imageOpen = Toolkit.getDefaultToolkit().createImage(u);

Another case

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("Images\\open.png");
imageOpen = Toolkit.getDefaultToolkit().createImage(resource);

Can any one tell me why am I getting null , I even tried "\\Images\\open.png" ,"/Images/open.png" and ".\\Images\\open.png" for the path I am using eclipse and the images are stored in the parent directory in a folder named Images and the source files are in src>master

use images/open.png . The forward slash works on any OS. Also, jar tvf your jar file to make sure the images directory is capitalized Images as you believe it to be. It may not be, and if you're on Windows (or a case-insensitive filesystem), it may work fine from the directory but not from a jar.

Are you sure url is null or does the problem come when using imageOpen?. Sometimes Toolkit.getDefaultToolkit().createImage() returns inmediatly but the image is not fully loaded and imageOpen is not usable. You need to wait for the image's load. This is the java code

JLabel label = new JLabel();
MediaTracker media = new MediaTracker(label);

Image imagen = Toolkit.getDefaultToolkit().getImage ("fichero.gif");
media.addImage(imagen, 23);
try
{
   media.waitForID(23);
}
catch (InterruptedException e)
{
   ...
}

借助于为jar创建资源包并从该文件中获取路径,我能够实现我的问题的解决方案

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.

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