Finding image in jar file

This took me by surprise:
I assumed that JVM would find image files, e.g. used in (JFrame).setIconImage(img) when these images are inside a jar file with the same path. I am using something like:
Image   icon=jframe.getToolkit().getImage(img_path);what works when running JVM with class files and images in directories, but not when in jar file. img_path is relative. Classes will be found as expected, but not the image files!
Do I do something wrong?
Thomas
Edited by: ThomasH_usually on Oct 1, 2008 11:48 AM

I encountered this same problem before, whereby I wanted to be able to run my code from within an IDE (find image files from the file system) for development, and also to be able to run my code from within an executable jar (find image files from inside the jar) for release. I used the following utility method to get an image URL:
public static URL getImageUrl(String fileName)
    // try to get the URL as a system resource
    URL url = ClassLoader.getSystemResource(fileName);
    if (url == null)
        // try to get the URL directly from the filename
        try
            url = new URL("file:" + fileName);
        catch (Exception e)
    return url;
}You can then use the resulting URL instead of the image path, in your case as follows:
Image   icon=jframe.getToolkit().getImage(Utils.getImageUrl(img_path));Paul.

Similar Messages

  • Applet : How to use Images in Jar file

    I want to put all images into a jar file to improve speed of loading.
    But how to invoke images from Jar file?
    Thanks.

    @Op. It's very important for a developer to know how to find information, and that skill usually comes with experience. Google is one of the best ways to find information and solutions to the most common problems.
    Kaj

  • Problem loading image from jar file referenced by jar file

    First, I searched this one and no, I didn't find an answer. Loading images from jar files has been pretty much done to death but my problem is different. Please read on.
    I have my application, a straight up executable running from Eclipse. It uses a jar file, call it JarA. JarA launches a GUI that is located in another jar file. Call it JarB. To recap:
    My application calls JarA -> JarA loads classes from JarB -> JarB looks for images to place in a GUI it wants to show on the screen
    When JarB goes to load an image the following happens:
    java.lang.NullPointerException
         at sun.misc.URLClassPath$3.run(URLClassPath.java:316)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:313)
         at sun.misc.URLClassPath.getLoader(URLClassPath.java:290)
         at sun.misc.URLClassPath.findResource(URLClassPath.java:141)
         at java.net.URLClassLoader$2.run(URLClassLoader.java:362)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findResource(URLClassLoader.java:359)
         at java.lang.ClassLoader.getResource(ClassLoader.java:977)
         at org.cubrc.gmshell.gui.MainWin.preInit(MainWin.java:152)
         at org.cubrc.gmshell.gui.MainWin.<init>(MainWin.java:135)
    The code from JarB that loads the image looks like this:
              URL[] oSearch = {Main.class.getResource("images/")};
              URLClassLoader oLoader = new URLClassLoader(oSearch);
              imgIcon = new ImageIcon(oLoader.getResource("icon.gif"));
              imgMatchRunning = new ImageIcon(oLoader.getResource("gears.gif"));
              imgMatchStill = new ImageIcon(oLoader.getResource("gears-still.gif"));
              imgMagnify = new ImageIcon(oLoader.getResource("magnify.gif"));This looks right to me and JarB certainly has an images directory with those files. But I'm in hell right now because I don't know where to place the images to make this work or if you can even attempt to load images with a dependency chain like this.
    Any help very appreciated!

    Have you tried to move your image-files out of the jar file and place them in the sam folder as the jar-file? I think that would help.
    When you try to load the image-file you get the NullPointerException because the program tries to read a file it can't find. Remember that a jar file IS a file and not a directory.
    If you want to read somthing inside the jar-file you need to encode it first.
    Have you tried to read the jar-file with winRar. It makes it easy to add and remove files in your jar-file.

  • Image on jar file

    i have a jar file
    on my desktop all jar file have the same icon
    i want to make a jar file with a personal icon
    how i can make this?

    You can change the icon for any type of file in windows. Java '.jar' files are no exception. By default jar files have a stupid icon that looks like a wordpad document (I think). I now use an icon of a coffee cup.
    Follow the second part of this document:
    http://www.adobe.com/support/techdocs/ac22.htm
    basically: In Windows Explorer. 
      From Menubar: Tools->Folder Options
      Goto "File Types" tab
      Find and select 'JAR' file in list
      Click 'Advanced' button. (DON'T click 'Change...' since that will
        try to change which application (javaw) is used to open jar files!
      In the resulting window, click the 'Change Icon...' button.  Select
        the icon of your choice.  Icons can be found in.
            .exe files will often have a list of icons embedded within them
            .dll files will also often have several
            .ico (windows icon files) include one or more
            and maybe you can use jpg or gif or other image format directly
               I don't know.Getting to the right dialog is slightly different depending on your version of windows. Read the article for more details.
    ...Chad

  • Add images in jar file

    how to add images in jar file?

    Check this article in ADF code corner:
    http://www.oracle.com/technetwork/developer-tools/adf/learnmore/86-images-from-jar-427953.pdf
    Thanks,
    Navaneeth

  • Reading Images from JAR Files

    Hi,
    I am having a very difficult time being able to read images from a JAR file via my Applet. I have tried everything that I know about with no luck. The only way I can get this to work is to store the images individually in a sub directory of public_html on the websever. This works, but I would like the images to come down in a JAR file for performance reasons.
    I am using Internet Explorer 5.5 for my browser. I checked the options and everything seems to be in order, but......
    I would appreciate any feedback that anyone might have on this topic..........
    Thank You....

    once in a jar file i inserted a image
    the jar file on clicking starts an frame.
    so the image was for getting that image at the icon place at top and at minimized window
    i could not get that image from jar file by new imageicon().getimage();
    but i get the image if it is in the directory in which jar file is.....
    can one explain the reason

  • Where to find newest interMedia jar file?

    I'm trying to implement the sample photo database servlet using Oracle's interMedia. In it, they use the method getFactory(), which has been deprecated. In place, they say to now use the method getORADataFactory(). However, I cannot seem to find the newest jar file which has this new method. Where can I find it and what is it's name? I've looked in the installation of Oracle 9i, but it still includes the old ordim.jar and ordim11.jar files.
    Thanks in advance.

    Ignore the deprecated error messsage. This is the supported way to interface with interMedia java in 9i

  • Images in Jar files

    Hi,
    I am creating a recipe book application. Everything is exactly how I want to so I am trying to make a jar file with it.
    On the first screen that loads there is one image, when I make the jar file it doesn't seem to be able to find the image once I am outside of eclipse and running the jar.
    I have created a folder in called resources in my scr folder (src/resources) this is where I am storing the image.
    The method near the bottom (private void addPic()) is where I am having troubles.
    package recipe1_5;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    * This provides an entry point into the program
    * as well as the first window
    * the main() function is at the bottom
    public class Main implements ActionListener {
         JFrame f = new JFrame();
         Container p = f.getContentPane();
         JButton newR = new JButton("Add a New Recipe");
         JButton oldR = new JButton("Look Up An Old Recipe");
         JLabel title = new JLabel("Please make a selection");
         public void actionPerformed(ActionEvent e){
              String whichButton = e.getActionCommand();
              if(whichButton.equals("Add a New Recipe")){
                   @SuppressWarnings("unused")
                   Recipe newRecipe = new Recipe();
                   f.setVisible(false);
                   f.dispose();
              if(whichButton.equals("Look Up An Old Recipe")){
                   @SuppressWarnings("unused")
                   OldRecipeChooser orc = new OldRecipeChooser();
                   f.setVisible(false);
                   f.dispose();
         }//END actionPerformed
         public Main(){
              f.setSize(200,300);
              f.setLocation(500,100);
              f.setTitle("Recipe Magic");
              p.setLayout(new FlowLayout());
              p.add(title);
              p.add(newR);
              p.add(oldR);
              newR.addActionListener(this);
              oldR.addActionListener(this);
              addPic();
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         }//END contr ChooseWindow()
         private void addPic(){
              try{
                   String imgLocal = System.getProperty("user.dir");
                   if(System.getProperty("os.name").contains("Windows")){
                        imgLocal += "\\RecipeMagic1_5.gif";
                        JOptionPane.showMessageDialog(null, imgLocal);
                   else
                        imgLocal += "/RecipeMagic1_5.gif";
                   BufferedImage image = ImageIO.read(new File(System.getProperty("user.dir" + imgLocal)));
                   JLabel pic = new JLabel(new ImageIcon(image));
                   p.add(pic);
              catch(Exception e){
                   JOptionPane.showMessageDialog(null, "Image Load Error","ERROR", JOptionPane.ERROR_MESSAGE);
                   e.printStackTrace();
         public static void main(String args[]){
              Main m = new Main();
    }//END class ChooseWindowI have tryed this two different ways. The first how it is. And the second with something like this:
    ImageIcon ii = new ImageIcon(getClass().getResource("resources/RecipeMagic1_5"));Any insight on how to get the image from inside of the jar file would be great
    Forgot to add, it either throws a NullPointerException or a FileNotFoundException in the catch clause of addPic()
    Edited by: tyelford on Dec 15, 2010 11:46 AM

    Ok, so it works good on Mac, but if I try to use it on Windows it will not load the image,
    Here is the code that works on Mac but not windows:
    private void addPic(){
              try{
                   String imgLocal = System.getProperty("user.dir");
                   if(System.getProperty("os.name").contains("Windows")){
                        imgLocal = "resources\\RecipeMagic1_5\\RecipeMagic1_5.gif";
                   else
                        imgLocal = "resources/RecipeMagic1_5/RecipeMagic1_5.gif";
                   ImageIcon ii = new ImageIcon(getClass().getResource(imgLocal));
                   JLabel pic = new JLabel(ii);
                   p.add(pic);
              catch(Exception e){
                   JOptionPane.showMessageDialog(null, "Image Load Error","ERROR", JOptionPane.ERROR_MESSAGE);
                   e.printStackTrace();
         }I get an Image Load Error on Windows, but the same file on Mac runs perfect

  • PJC - Loading Images from JAR Files

    I'm developing a PJC class that involves loading images. I would like to be able to find and use an image contained in a JAR file just like the built-in Forms items do; not the JAR file where my class is contained but any external ones defined in the server archive settings.
    I have seen the loadImage method in the demo RolloverButton class but this only loads images from the class's JAR and not any others.
    Is there a VButton method or an Oracle loader class for finding image resources from the defined JAR archives? If not, could someone supply some code for achieving this.
    Thank you.

    Hi,
    the jar file name the images are in shouldn't matter for the code as long as the package name is preserved. If you want to see it with your own eyes, do the following
    1. Back up demo90.jar
    2. Create a copy of it and call it demo90img.jar
    3. Open demo90.jar in winzip and remove all images
    4. Open demo90img.jar and remove all Java classes
    5. add ,/forms90demo/jars/demo90img.jar to the archive_jini tag of a demo you want to test this on
    6. Run the application and see the images despite the fact they are now in a separate jar file. Note in the Jinitiator console that the new jar files are downloaded and replace the existing, cached, jars
    7. Run an application that doesn't have demo90img.jar configured to see that the images are missing.
    Frank

  • How do i find and download jar files?

    I have some old code and it uses import com.sun.java_cup.internal.parser
    When compiling gives error on this.
    Googleing this shows that its part of the rt.jar file. rt.jar is in the jre/lib folder. That is part of my classpath but still wont compile how do i find what an import belongs to and where can i download these jar files..
    Java really is not a friendly language to me.

    You don't need to download the rt.jar or do anything with it since it's an integral part of the JRE. If a class isn't there, then because you have too old a JRE/JDK and it's not there yet, or because it was never part of the public API and is gone now.
    When I google, I only find references to Java 6. So you probably need that, which means the sources can't be sooo old.

  • Problem with images in .jar file

    Hi all!
    I've got a severe problem when deploying an application via web start:
    the images withhin a deployed .jar file are not found.
    So far I've tried a number of things to get the images back, none of which are working.
    I've found different threads concerning this topic, e.g.:
    http://forum.java.sun.com/thread.jspa?threadID=396363
    http://forum.java.sun.com/thread.jspa?threadID=465795&messageID=2141351
    but sadly, they didn't help me out.
    Here is my code I'm using:
      private ImageIcon loadIconFromClassLoader(String tszRelPath)
        ImageIcon tIcon = null;
        cCat.info("tszRelPath = "+ tszRelPath);
        // this line simply leads to a crash of the whole application
        //tszRelPath = tszRelPath.replaceAll("\\", "/");
        if(!tszRelPath.startsWith("/"))
          tszRelPath = "/" + tszRelPath;
        cCat.info("modified tszRelPath = " + tszRelPath);
        URL tURL = ClassLoader.getSystemResource(tszRelPath);
        if(tURL == null)
          // this too crashes my application
          //tURL = PlainResourceProvider.class.getResource(tszRelPath);
        if(tURL != null)
          tIcon = new ImageIcon(tURL);
        return tIcon;
      }I've also tried
    PlainResourceProvider.class.getClassLoader().getResource()PlainResourceProvider is part of the .jar that involves the images.
    Of course all the .class files in the .jar file are easily accesible
    I would be so thankful, if just anyone could help me to solve this problem.
    I am going crazy.
    Thanks in advance, Christoph

    You should take care of the directory structure according to the package structure.
    I for example have this jar:
    C:\source\java\ebank2_util\smsunlock>unzip -l pro-ebank_sms_unlock.jar
    Archive:  pro-ebank_sms_unlock.jar
    Length    Date    Time    Name
          0  10-28-05  17:27   hu/
          0  10-28-05  17:27   hu/khb/
          0  10-28-05  18:17   hu/khb/smsunlock/
        256  11-07-05  16:33   hu/khb/smsunlock/DButils$MySQLException.class
       4229  11-07-05  16:33   hu/khb/smsunlock/DButils.class
       1700  11-07-05  16:33   hu/khb/smsunlock/GUI$1.class
       2318  11-07-05  16:33   hu/khb/smsunlock/GUI$2.class
        988  11-07-05  16:33   hu/khb/smsunlock/GUI$3.class
       1402  11-07-05  16:33   hu/khb/smsunlock/GUI$mywl.class
       5630  11-07-05  16:33   hu/khb/smsunlock/GUI.class
        818  11-07-05  16:33   hu/khb/smsunlock/LimitedLength_TextField.class
       2452  11-07-05  16:33   hu/khb/smsunlock/Main.class
        900  11-07-05  16:33   hu/khb/smsunlock/MyInputStream.class
          0  11-07-05  16:33   META-INF/
         98  10-27-05  15:53   META-INF/manifest.mf
         90  11-07-05  16:33   hu/khb/smsunlock/properties
      20881                    16 filesAnd the resource is loaded like this from hu.khb.smsu.Main:
    InputStream is = new MyInputStream( Main.class.getResourceAsStream( "properties" ) );

  • Images in .jar file , "NullPointerException"

    Hi,
    How do I show images which are present in .jar file.
    e.g
    Toolkit tKit = Toolkit.getDefaultToolkit();
    URL logo = MyTool.class.getResource("images/icon.gif");
    Image g1=tKit.getImage(logo);
    this.setIconImage(globalleafs1);
    this works both in c:\java MyTool
    and while created in a .jar file
    But when I use it for ImageIcon in a button, I get "NullPointerException" while working in a .jar file.
    Here are the methods that I have tried to get it worked
    1.
    new2 = new JButton(new ImageIcon(ClassLoader.getResource("images/new.gif")));
    2.
    URL newim = MyTool.class.getResource("images/new.gif");
    new2 = new JButton(new ImageIcon(newim));
    But it too dont work. Please help me.

    This came up recently -it was solved with MedaiTracker()
    Check back a few pages

  • Problem finding class in jar file

    I have an applet that will run when I have all the classes sitting in the same directory. ex) http://IPaddress/directory. But I try to put them all into a jar file and run the code and it says cant find the class. Below is my html code. Please help!
    <HTML>
    <HEAD>
    </HEAD>
    <BODY>
    <APPLET
    CODEBASE="http://IPaddress/directory1/directory2"
    CODE="Applet.class"
    ARCHIVE="1stJar.jar,2ndJar.jar,3rdJar.jar,Applet.jar"
    WIDTH=600 HEIGHT=600>
    </APPLET>
    </BODY>
    </HTML>

    Where are your jar files contained? They need to be in the same directory as your CODEBASE, or otherwise include a relative directory.
    Also, what browser are you using?
    From the Java web page on APPLET tags
    "Unfortunately, not all browsers understand the same archive format or use the same HTML code to specify the applet archive"

  • Including images in jar executable files. Using images in jar files.

    Does anybody know what is the reason of my problem??
    I created a package called test in my eclipse env. and in that package I placed folder named graph in which there is a file Help.png.
    Here is all the code I run in eclipse and it runs properly. When I create a jar file (using eclipse wizard) to execute without eclipse it can not execute and shows nothing (process starts and I have to kill it by myself in OS). Maybe there is some mistake with making jar... I do not know
    So let someone try tu run my class or build jar file and try to execute and share his observations (solutions) ??
    package test;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    public class TestWindow extends JFrame {
         private JButton jButton1 = new JButton(new JARImage().getImage("Help.png"));
         public TestWindow() {
              this.getContentPane().add(jButton1);
              this.validate();
              this.setVisible(true);
         private class JARImage {
              protected ImageIcon getImage(String imageName) {
                   ImageIcon image = new ImageIcon();
                   try {
                        image.setImage((Toolkit.getDefaultToolkit().getImage(getClass()
                                  .getResource("graph/" + imageName))));
                   } catch (Exception ex) {
                        System.out.println("Image Error: " + ex);
                        ex.printStackTrace();
                   return image;
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              new TestWindow();
    }

    Uncaught error fetching image:
    java.lang.NullPointerException
         at sun.awt.image.URLImageSource.getConnection(Unknown Source)
         at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
         at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
         at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
         at sun.awt.image.ImageFetcher.run(Unknown Source)

  • How to dynamically find the dependent jar files on user's PC

    I've written an application to deal with JTAPI. Unfortunately the implementations by vendors are different in terms of file names. Ideally I'd like to load jars based upon what's installed, e.g. load jtapi.jar when Cisco is installed, or Escjtapia.jar when it's Avaya. The application uses a small subset of JTAPI so different implementations should not yield any different results.
    I edited the manifest file in my jar so that the Class-path has both jar file names for Cisco and Avaya. I didn't enter any path, hoping the CLASSPATH of Windows would be searched, but it is not the case. Also, if other vendors are supported in the future, I might have to add all different file names in the manifest. I don't think the class loader will work in my case, as I may not know the class name at all. I just want to search the system's classpath the find any jar complys to JTAPI and load it.
    Anybody can give suggestions on deployment? Thanks!

    I found it. EXIT_SAPLV01Z_001 does the trick. A package contains many User-Exits, BADIs and enhancement points, so it took me a while to go thru all of them.

Maybe you are looking for