Loading icons from a jar

Hi all,
I've got my application that loads icons from a relative path, such as "img/tree/menu.png". While running outside the jar it works fine, but when I create a jar of my filesystem I cannot load the icon (i.e., it is not found). The jar of course contains the icons and the relative path.
Anybody has a clue about?
Thanks,
Luca

I am loading the images for my application. For my application in development phase - I am putting the image in the source folder as well as in the jar file.
Here is the code I am using
try
               URL url = this.getClass().getClassLoader().getResource(imageName);
               if (url == null)
                    url = new File(imageName).toURL();
               JLabel logo = new JLabel(new ImageIcon(url));image name is the name of the image say "xyz.gif"
In the jar file just include the image files and it should work fine.

Similar Messages

  • Loading icons from jar file

    Hello,
    i am trying to load ALL imagefiles from my jar file. i do the following:
    Class clazz = Class.forName("com.xxx.IconSelectionDialog");
    String me = clazz.getName().replace(".", "/") + ".class";
    dirURL = clazz.getClassLoader().getResource(me);
    if (dirURL.getProtocol().equals("jar")) {
    String jarPath = dirURL.getPath().substring(6, dirURL.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(jarPath );
    Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
    while (entries.hasMoreElements()) {
    JarEntry nextEntry = entries.nextElement();
    String jarEntryName = nextEntry.getName();
    this works fine with my debug local jws installation. when i try to run it online starting i get an error:
    java.io.FileNotFoundException: xentis.jar (Das System kann die angegebene Datei nicht finden)
         at java.util.zip.ZipFile.open(Native Method)
         at java.util.zip.ZipFile.<init>(ZipFile.java:114)
         at java.util.jar.JarFile.<init>(JarFile.java:133)
         at java.util.jar.JarFile.<init>(JarFile.java:70)
    how can i load ALL icons from a jar (without knowing the filename) ?
    is there a generic way to iterate over all entries of a jarfile ?
    thank you
    michael

    Look at "Loading Images Using getResource" on this page
    http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html
    It should provide some ideas.

  • Issues with Loading Images from a Jar File

    This code snippet basically loops through a jar of gifs and loads them into a hashmap to be used later. The images all load into the HashMap just fine, I tested and made sure their widths and heights were changing as well as the buffer size from gif to gif. The problem comes in when some of the images are loaded to be painted they are incomplete it looks as though part of the image came through but not all of it, while other images look just fine. The old way in which we loaded the graphics didn't involve getting them from a jar file. My question is, is this a common problem with loading images from a jar from an applet? For a while I had tried to approach the problem by getting the URL of the image in a jar and passing that into the toolkit and creating the image that way, I was unsuccessful in getting that to work.
    //app is the Japplet
    MediaTracker tracker = new MediaTracker(app);
    //jf represents the jar file obj, enum for looping through jar entries
    Enumeration e = jf.entries();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    //buffer for reading image stream
    byte buffer [];
    while(e.hasMoreElements())
    fileName = e.nextElement().toString();
    InputStream inputstream = jf.getInputStream(jf.getEntry(fileName));
    buffer = new byte[inputstream.available()];
    inputstream.read(buffer);
    currentIm = toolkit.createImage(buffer);
    tracker.addImage(currentIm, 0);
    tracker.waitForAll();
    images.put(fileName.substring(0, fileName.indexOf(".")), currentIm);
    } //while
    }//try
    catch(Exception e)
    e.printStackTrace();
    }

    compressed files are not the problem. It is just the problem of the read not returning all the bytes. Here is a working implementation:
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    try{
    byte[] buf = new byte[1024];
    int read;
    while((read = is.read(buf)) > 0) {
    os.write(buf, 0, read);
    catch(Exception e){
         e.printStackTrace();
         return null;
    image = Toolkit.getDefaultToolkit().createImage(os.toByteArray());
    This works but I think you end up opening the jar a second time and downloading it from the server again. Another way of getting the images is using the class loader:
    InputStream is = MyApplet.class.getResourceAsStream(strImageName);
    In this case, the image file needs to be at the same level than MyApplet.class but you don't get the benefit of enumerating of the images available in the jar.

  • Loading icons from jar - linux problem

    Dear,
    I use the folowing code to load an iconImage from a jar file to be used on JButtons:
    private ImageIcon getImageIcon(String iconName){ //gets icon from a file
    ImageIcon icon = null;
    ClassLoader cl = this.getClass().getClassLoader();
    java.net.URL imageURL = cl.getResource("/ExcelInterface/rsrc/"+iconName);
    if (debug) System.out.println(imageURL.toString());
    try{
    if (imageURL != null) {
    icon = new ImageIcon(imageURL);
    }catch (Exception e){
    System.out.println(e.getMessage());
    return icon;
    } // end of getImageIcon(String iconName)
    this works fine on windows.
    On linux everything looks fine (i.e. there are no exceptions, the URL looks fine...) BUT the Icons are not displayed on the buttons.
    Anyone have an idea why?

    I do something similar and although I've never had any problems on Linux only the server side stuff runs there so I've never tried exactly what you are doing. Anyway, my code doesn't have the leading "/" on the URL and the URL is the full path name from the class root, literally "com/inqwell/any/client/arrowup.gif" in my case. Try that and see if it works.

  • Loading Resources from a .JAR

    I've read through this forum and searched java.sun.com and have found nothing to solve my problem, although I see many other people are having the same problem.
    I wrote a small application that needs to load a text file and images. When I just compile everything and then run it, all is well, my text file is found and my images are displayed. Now the problem is when I package everything into a .JAR file, suddenly my magic stops. Here is the directory structure
    - State.class
    FiftyStatesGame.class
    FlagPanel.class
    StatsPanel.class
    StatePanel.class
    states.txt
    /images
    /flags
    a bunch of .gif images (50 total)
    /states
    a bunch of .gif images (50 total)
    I create my archive with the following command
    jar cvf FiftyStates.jar *
    and all seems well, I've even changed the extension to .zip to ensure that the images and text file is inside the jar
    Now when I try to run the program using
    java -cp FiftyStates.jar FiftyStatesGame
    the program starts but I get a NullPointerException and my pictures don't load. :-(
    I've read in the forum about using
    URL imageURL = ClassLoader.getSystemResource(<path to image>);
    Image logo = Toolkit.getDefaultToolkit().getImage(imageURL);
    and I tried this and once again, it works when not in jar form, but as soon as the application is JARed, I encounter the same problems.
    Can anyone give me the answer to this crazy problem?
    and I guess I should go one step further and ask, if I want to give this program to a friend with the JRE installed on a windows machine, what command should I put in my batch file to run this program on his machine?
    javaw -cp FiftyStates.jar FiftyStatesGame
    Thanks for any help and advice

    Hi,
    Getting the image
    =================
    It seems to me you can't be too far away from resolving your problem.
    I've never actually tried to get an image from a jar file, so I'm guessing that this may not work for you, but I have unzipped a zip file contained within an executable jar.
    What I did was this:
        private ZipInputStream findInstallationFile() {
            ClassLoader classLoader;
            URL url;
            ZipInputStream zipInputStream = null;
            InputStream inputStream;
            classLoader = getClass().getClassLoader();
            url = classLoader.getResource(ZIP_RESOURCE_NAME);
            if (url != null) {
                try {
                    inputStream = url.openStream();
                    zipInputStream = new ZipInputStream(inputStream);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
            } else {
                System.err.println("Failed to find resource: " + ZIP_RESOURCE_NAME);
            return zipInputStream;
        }The good thing about this is that you can see whether or not the resource was found in the jar file. If the returned URL is null, then the resource isn't there.
    Once you have the InputStream, you can just read the entire contents and do what you like with them.
    Executable jars
    ===============
    You can make it easier to run a jar file by including a manifest file. This is just a text file which should be in the META-INF directory in your jar file. The manifest file itself should be called Manifest.mf.
    The contents of the Manifest should be:
    Manifest-Version: 1.0
    Main-Class: FiftyStatesGame
    This assumes that your main class is FiftyStatesGame which is in the default package (tut, tut!).
    Hope this helps!
    Rhys

  • Is it possible to load classes from a jar file

    Using ClassLoader is it possible to load the classes from a jar file?

    URL[] u = new URL[1] ;
    u[0] = new URL( "file://" + jarLocation + jarFileName + "/" );
    URLClassLoader jLoader = new URLClassLoader( u );
    Object clsName = jLoader.loadClass( clsList.elementAt(i).toString() ).newInstance();
    I get this error message.
    java.lang.ClassNotFoundException: ExceptionTestCase
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    // "file://" + fileLocation + fileName + "/" This works fine from a browser.
    Is there anything I am missing? Thanks for the reply.

  • Loading classes from another jar file

    I've set up my jnpl file so that it references a core jar file (contains main() function). The jnlp also references another jar file (app.jar) which contains class files that I load and instantiate dynamically (using ClassLoader). The core.jar file contains a manifest that includes a reference to app.jar.
    The app works fine when I use "java -jar core.jar" from the command line.
    However, when I wrap the jars using jnlp, I always get a null pointer exception because it cannot find any class that is in the app.jar file. I've tried different strategies, such as trying to load a class file that sits on the server (in a jar file and not in a jar file), but that also fails if I use jnlp (However, it works if I use "java -jar core.jar")
    Any ideas what is going on?

    This is the "OckCore.jar" manifest before signing:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Class-Path: . OckMaths.jar
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Name: com.Ock.OckCore.OckApp.class
    Java-Bean: FalseThis is the manifest after signing:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Class-Path: http://hazel/Ock/. http://hazel/Ock/OckMaths.jar
    Name: com/Ock/OckCore/OckApp.class
    SHA1-Digest: KRZmOryizx9o2L61nN+DbUYCgwo=I have removed a load of irrelevant stuff from the "after" manifest to keep it readable.
    note that :-
    The OckApp.class loads normally from webstart and tries to load a class from OckMaths.jar.
    I can prove that OckApp.class does load because it creates a log file when it does.
    The OckApp.class tries to load a class from the OckMaths.jar. This fails if webstart is used but works if OckCore is launched using "java -jar OckCore.jar".
    The jars do exist at the location specified by the manifest.
    The application launches normally if I use "java -Jar OckCore.jar"
    Here is the jnlp file
    <?xml version='1.0' encoding='UTF-8'?>
    <jnlp
         spec="1.0"
         codebase="http://hazel/Ock"
         href="OckMaths.jnlp">
         <information>
              <title>Ock Maths Demo</title>
              <vendor>Rodentware Inc</vendor>
              <description>Demo of a ported app running as a Java Webstart application</description>
              <description kind="short">An app running as a Java Webstart application"></description>
              <offline-allowed/>
         </information>
         <security>
              <all-permissions/>          
         </security>
         <resources>
              <j2se version="1.3"/>
              <jar href="OckCore.jar"/>
              <jar href="OckMaths.jar"/>
         </resources>
         <application-desc main-class="com.Ock.OckCore.OckApp">
    </jnlp> I have also signed the jars outside of a webdirectory. I get the following manifest file:
    Manifest-Version: 1.0
    Main-Class: com.Ock.OckCore.OckApp
    Created-By: 1.4.0-beta3 (Sun Microsystems Inc.)
    Class-Path: . OckMaths.jar
    Name: com/Ock/OckCore/OckApp.class
    SHA1-Digest: KRZmOryizx9o2L61nN+DbUYCgwo=
    note that :-
    The jars do exist at the location specified by the manifest.
    The application launches normally if I use "java -Jar OckCore.jar".
    The application doesn't launch from webstart.
    I've found that cache, but the jar files have been renamed.
    OckCore.jar is anOckCore.jar, etc... so I'm not sure if trying to write a cmdline will work anyway.

  • Iconic buttons in design time ... Is there any way to take their icons from the jar or at least from gif files?

    I've put my button icons in a signed gif, and they work fine at runtime.
    The problem is at design time, I can't get to see their icons properly.
    I have to convert the gifs to ico and place them in a folder referenced by the old UI_ICON registry variable.
    Also, as the gifs are 16x16, they are cropped in design time, because I see them as if they where stretched to 32x32 size.
    At least it would be enough if I could place the gifs directly somewhere, without converting to ico.
    It seems as if oracle had not put any development work in the builder, which is like a direct port from the 6i c/s version.

    Since you didn't mention exactly which Forms version you are using, I will guess and assume it is one of the many versions after 6.0.8.  The Forms Builder 9.x+ supports ico, jpg, and gif files.  It will not however read them from a jar.  Therefore, you will need to extract them into a directory as defined by UI_ICON.  Also, the files will need to be of the same type (gif, jpg, ico).  Mixing formats is not recommended or supported.  The format you choose can be defined in UI_ICON_EXTENSION
    So for example in your Registry you might have something like this:
    UI_ICON = C:\myImagesDirectory
    UI_ICON_EXTENSION = gif
    Since "gif" is the default, you do not need to set this if using "gif" files.

  • Loading images from a jar file

    Hi,
    My application displays images, until it's placed in a JAR file, then it can't display them even though the JAR file contains the images.
    I saw this problem in a previous question which was solved using
    URL url = MyClass.class.getResource("abc.gif");
    Image img=Toolkit.getDefaultToolkit().getImage(url);
    ....which btw didn't work for me either......
    This method should be made obsolete using ImageIcon, which I am using, but the images still won't appear...
    Any suggestions?

    It works fine that way (...getClass().getResource....) until I create the jar file, and then I get a null pointer exception when it tries to load the image.
    When I use
    javax.swing.ImageIcon icon = new javax.swing.ImageIcon(("/images/imageName.jpg"));
    the application works but without the images.......

  • Loading images from a JAR

    Hi,
    My class is currently stored in a subdirectory of my JAR file, and in the directory with the class is a "textures" directory, containing all of my images.
    When I run my class from the directory before I zip it up to be a JAR, it works fine. But, as soon as I run it as a JAR file, it crashes when loading the images.
    Here's the code I'm using to load the images:
    BufferedImage temp = null;
    String path = this.getClass().getResource("textures/" + imagePath).toString();
    temp = ImageIO.read(new File(new URI(path)));What am I doing wrong?
    Thanks for any assistance! =)

    Hiii bro ,
    I think this will help u ,,,,,,,,
    suppose you have a folder Image , under that folder there are some image files and you have a main class say TestMain.class .
    In your main class(TestMain)
    import javax.swing.ImageIcon;
    Now write this code into your main class----------->
    public ImageIcon customOpenIcon = new ImageIcon(TestMain.class.getResource("/image/expanded.gif"));Thanks,
    sb

  • How To Load Sound From Inside jar File?

    Hello There
    i've made a jar file that contains Images&Pictures But I Can't Use Them
    So I Used For Loading Images
      URL url = this.getClass().getResource("image.jpg");
             setIconImage(new ImageIcon(url).getImage());and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
           AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?

    First_knight wrote:
    and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?Remove the "new File()". There is a getAudioInputStream() method that takes a URL.
    AudioInputStream in = AudioSystem.getAudioInputStream(url);

  • Need help getting icons from jar

    I switched to the latest java plugin, 1.4.2 and now I can't get the applet to retrieve the GIF image within its jarfile. The class files and imagery are all located in the same jarfile. If I use the following code:
    ivjJToggleButton20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/MoveVertex2.gif")));
    The jarfile is downloaded again and the image is retrieved from the downloaded jarfile instead of the jar currently displayed in the browser.
    any help or ideas are greatly appreciated!

    I usually do something like this to load an icon from a JAR:
    java.net.URL iconURL = getClass().getResource("/yourImageFile.gif");
    if (iconURL != null) icon = new javax.swing.ImageIcon(iconURL);
    JButton.setIcon(icon);
    This should work.

  • Loading image from jars only once in oracle forms 10g

    Hi,
    I have an oracle forms 10g application which loads image from a jar. Every time i click on a button "A" that loads the image "image" on another button "B" in the same screen, a message is displayed in the java console "Loaded image: jar:https://+IP+/forms/java/+myjar+.jar!/image.gif". So after 10 clicks, i get the same message displayed 10 times. In the form, i've called:
    SET_CUSTOM_PROPERTY(p_object_name, 1, 'IMAGE_NAME_ON', '/'||p_image_name);My question is the following:
    - is there a way to load this image once and use it later without having to load it every time i clik on "A"? if yes, how?
    P.S.: if this thread shouldn't be posted in this forum, please redirect me to the right one.
    Thanks in advance

    Ah okay.
    I'm using the rolloverbutton.jar (RollOver Button PJC) [RolloverButton.java -> authors: Steve Button, Duncan Mills].
    Here is the part concerning the IMAGE_NAME_ON function:
    // make sure we are in rollover mode
    enableRollover();
    log("setProperty - IMAGE_NAME_ON value=" + value.toString());
    // load the requested image
    m_imageNameOn = (String) value;
    loadImage(ON,m_imageNameOn);
    // reset the currrently drawn image if needed
    setImage(ON,m_state);
    return true;where loadImage function is:
        URL imageURL = null;
        boolean loadSuccess = false;
        //JAR
        log("Searching JAR for " + imageName);
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          log("URL: " + imageURL.toString());
          try
            m_images[which] = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            log("Image found: " + imageURL.toString());
          catch (Exception ilex)
            log("Error loading image from JAR: " + ilex.toString());
        else
          log("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          log("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
              log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          log("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            log("Constructed URL: " + imageURL.toString());
            try
              m_images[which] = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              log("Image found: " + imageURL.toString());
            catch (Exception ilex)
                    log("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            log("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          log("Error image " + imageName + " could not be located");In this case, what shall i modify?
    Thanks in advance

  • Pulling WSDL from local JAR

    Hi!
    For my web service wsdl is generated automatically. I want to load wsdl from
    local JAR at runtime, and not to make a long trip to the server. I guess I
    have to set proper <soap:address location=... > in the local wsdl. But I
    cannot understand how this location attribute is generated. There are names
    in this attribute that I never set in my build files, like "myWebService".
    How to tune up <soap:address location=... > attribute? And I still want to
    use autogenerated wsdl.
    Thanks,
    Michael.

    Pls try setting the following attribute in the ant
    task:
    servicegen->client->defaultEndPoint="http://your.server/your-service"
    regards,
    -manoj
    "Michael Jouravlev" <[email protected]> wrote in message
    news:[email protected]..
    Hi!
    For my web service wsdl is generated automatically. I want to load wsdl from
    local JAR at runtime, and not to make a long trip to the server. I guess I
    have to set proper <soap:address location=... > in the local wsdl. But I
    cannot understand how this location attribute is generated. There are names
    in this attribute that I never set in my build files, like "myWebService".
    How to tune up <soap:address location=... > attribute? And I still want to
    use autogenerated wsdl.
    Thanks,
    Michael.
    [att1.html]

  • Problem loading image icons from jar

    I have created an Applet , that works as an application too.I created the certificate the jar, with the images and the classes, i signed it... The html page is working fine as the exe i have made from the jar, but ONLY if the folder with the images is in the same directory!!!I have searched in java and other forums for an answer that fits but..
    Here is a sample of my code.
    images[0]=new ImageIcon((Applet15.class.getResource("/palaio/Image8.jpg")));
    images[1]=new ImageIcon((Applet15.class.getResource("/palaio/Image22.jpg")));
    images[2]=new ImageIcon((Applet15.class.getResource("/palaio/Image30.jpg")));
    images[3]=new ImageIcon((Applet15.class.getResource("/palaio/Image36.jpg")));
    images[4]=new ImageIcon((Applet15.class.getResource("/palaio/Image42.jpg")));
    images[5]=new ImageIcon((Applet15.class.getResource("/palaio/Image63.jpg")));
    public Applet15() {
          private void jbInit() throws Exception {
      public String getAppletInfo() {
        return "Applet Information";
      public String[][] getParameterInfo() {
        return null;
      public static void main(String[] args) {
        Applet15 applet = new Applet15();
        applet.isStandalone = true;
        Frame frame;
        frame = new Frame();
        frame.setTitle("Applet Frame");
        frame.add(applet, BorderLayout.CENTER);
        applet.init();
        applet.start();
        frame.setSize(450,400);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
        frame.setVisible(true);Thank you!!

    This tutorial should resolve the problem
    http://java.sun.com/docs/books/tutorial/applet/appletsonly/data.html

Maybe you are looking for

  • A challange: creating a movie player in a panel

    so.. one of my colleagues has thrown me the gauntlet to create a functional movie player as a indesign panel. Is it even possible using javascript? i'm thinking that i can use a flashplayer scriptUI object maby?

  • Can't delete calendars or events from iCal

    I'm trying to delete Calendars from iCal, but after I delete them, they reappear. I've tried deleting the calendars and calendar cache from the user library, but to no avail. In addition, when I try to change or delete an event, it ends up duplicatin

  • Java.lang.UnsatisfiedLinkError: t2cGetCharSet Error in ODI

    Hi Experts, I am trying to create Oracle Data Server . The source is Oracle E-Business Suite R12. When i click on test connection i get an error message "java.lang.UnsatisfiedLinkError: t2cGetCharSet". Any idea why such error. Thanks and Regards, And

  • Ink levels no longer viewable

    The ink levels are no longer viewable since I installed windows 7.  Any help  Thanks

  • Upgrading LiveCycle 8.0.1 SP3 to 8.2

    Hi, I need to upgrade my Live Cycle ES version 8.0.1 SP3 to LiveCycle ES v8.2. There is my environment : - JBoss v4.0.3SP1 - SQL Server 2005 SP1 - Windows Server Standard Edition 2003 R2 SP1 So, my issue is that in the prepareupgrade_8x.pdf they said