Pictures in Jar file

Hi !
How can I do ?
I have a jar file in wich there are pictures.
This jar file is located at c:/files/myjar.jar
I have a JeditorPane wich manage very well HTML. I would like it to show one of my pictures placed in my jar file.
I did this but it does not work :
<img src="c:/files/myjar.jar/mypicture.gif">
or
<img src="c:/files/myjar.jar!/mypicture.gif">
What's wrong please ? Or How can I link something located in a jar file ?

this.getResource("relative path");
is finds you class that you are running and then get the file at eh sub directory to it
so if you jar file is in c:\a\b\c
and the image is in c:\a\b\c\d
all you have to do is
this.getResource("d\file name");
this should get you started

Similar Messages

  • How to access picture in jar file?

    i,ve made a jar file containing folder named frame\\data
    and the folder data containing picture and sound
    and i want to call\access the picture and the sound to make them appear to the user how?
    this is my code
    import java.io.*;
    import java.net.URL;
    import java.awt.*;
    import javax.swing.ImageIcon;
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.AbstractButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionEvent;
    import javax.swing.JFrame;
    import javax.sound.sampled.*;
    import java.awt.event.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
      public class MyFrame extends JFrame 
    ImageIcon img =new ImageIcon("src\\frame\\data\\heart7.png");
    JButton btn=new JButton("Press Me", img);
      MyInner inner;
        MyInner4 inner4;
          MyFrame ()
            setupGUI();
        private void setupGUI()
           JFrame f =new JFrame();
        //   f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
           f.setTitle("Window Event");
            f.setSize(550,350);
            f.setResizable(false);
            f.setLayout(new BorderLayout());
            f.add("Center",btn);
              btn.setVerticalTextPosition(AbstractButton.BOTTOM);
              btn.setHorizontalTextPosition(AbstractButton.CENTER);
            f.setVisible(true);
             inner=new  MyInner();
             inner4=new  MyInner4();
             f.addWindowListener(inner);
             f.addWindowListener(inner4);
             class MyInner extends WindowAdapter
            public void windowClosing(WindowEvent ee)
                Toolkit tool = Toolkit.getDefaultToolkit();
                tool.beep();
                JOptionPane.showMessageDialog(null, "Better Work!","Bye Bye",JOptionPane.INFORMATION_MESSAGE,img);
               // JOptionPane.showMessageDialog(null, "Text", "Title", JOptionPane.Type, icon);
                System.exit(0);
            class MyInner4 extends WindowAdapter
          public void   windowOpened(WindowEvent ex)
             try {
            // From file
            AudioInputStream stream = AudioSystem.getAudioInputStream(new File("src\\frame\\data\\BraveHeart.wav"));
            // From URL
            //stream = AudioSystem.getAudioInputStream(new URL("http://hostname/audiofile"));
            // At present, ALAW and ULAW encodings must be converted
            // to PCM_SIGNED before it can be played
            AudioFormat format = stream.getFormat();
            if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                format = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        format.getSampleRate(),
                        format.getSampleSizeInBits()*2,
                        format.getChannels(),
                        format.getFrameSize()*2,
                        format.getFrameRate(),
                        true);        // big endian
                stream = AudioSystem.getAudioInputStream(format, stream);
            // Create the clip
            DataLine.Info info = new DataLine.Info(
                Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
            Clip clip = (Clip) AudioSystem.getLine(info);
            // This method does not return until the audio file is completely loaded
            clip.open(stream);
            // Start playing
            clip.start();
            // Play and loop forever
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        /* Play and repeat for a certain number of times
        int numberOfPlays = 3;
        clip.loop(numberOfPlays-1);
         catch (IOException e) {
        } catch (LineUnavailableException e) {
        } catch (UnsupportedAudioFileException e) {
          public  static void main(String[]args)
             MyFrame frame=new MyFrame ();
    }

    Instead of doing like this,
    ImageIcon img =new ImageIcon("src\\frame\\data\\heart7.png");
    JButton btn=new JButton("Press Me", img); use this code,and then prepare the jar
    try{
    URL pathShell = null;
    Object dummy = new Object(){
         public String toString() { return super.toString(); }
    ClassLoader cl = dummy.getClass().getClassLoader();
    pathShell  = cl.getResource("src\\frame\\data\\heart7.png");
    image = new ImageIcon(pathShell);
    JButton btn=new JButton("Press Me", imgage);
    catch (Exception e) {}

  • Applet that archieve jar file fail to load picture

    hello...
    i already can display my applet , but the ploblem is the applet canot display the picture...
    the class that i include in the jar file is can run and will display the picture...
    wat is the ploblem?
    thanks...

    This is my full code
    package dir.yew;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class DirTree
         extends JPanel {
         public static final String APP_NAME = "Directories Tree";
         public static final ImageIcon ICON_COMPUTER =
              new ImageIcon("computer.gif");
         public static final ImageIcon ICON_DISK =
              new ImageIcon("disk.gif");
         public static final ImageIcon ICON_FOLDER =
              new ImageIcon("folder.gif");
         public static final ImageIcon ICON_EXPANDEDFOLDER =
              new ImageIcon("expandedfolder.gif");
         protected JTree  m_tree;
         protected DefaultTreeModel m_model;
         protected JTextField m_display;
         public DirTree() {
              DefaultMutableTreeNode top = new DefaultMutableTreeNode(
                   new IconData(ICON_COMPUTER, null, "My Computer"));
              DefaultMutableTreeNode node;
              File[] roots = File.listRoots();
              for (int k=0; k<roots.length; k++) {
                   node = new DefaultMutableTreeNode(new IconData(ICON_DISK,
                        null, new FileNode(roots[k])));
                   top.add(node);
                node.add( new DefaultMutableTreeNode(new Boolean(true)));
              m_model = new DefaultTreeModel(top);
              m_tree = new JTree(m_model);
              m_tree.putClientProperty("JTree.lineStyle", "Angled");
              IconCellRenderer renderer = new
                   IconCellRenderer();
              m_tree.setCellRenderer(renderer);
              m_tree.addTreeExpansionListener(new
                   DirExpansionListener());
              m_tree.addTreeSelectionListener(new
                   DirSelectionListener());
              m_tree.getSelectionModel().setSelectionMode(
                   TreeSelectionModel.SINGLE_TREE_SELECTION);
              m_tree.setShowsRootHandles(true);
              m_tree.setEditable(false);
                   JScrollPane splitPane = new JScrollPane(
              new JScrollPane(m_tree)
              setLayout( new BorderLayout() );
              add( splitPane );
         DefaultMutableTreeNode getTreeNode(TreePath path) {
              return (DefaultMutableTreeNode)(path.getLastPathComponent());
         FileNode getFileNode(DefaultMutableTreeNode node) {
              if (node == null)
                   return null;
              Object obj = node.getUserObject();
              if (obj instanceof IconData)
                   obj = ((IconData)obj).getObject();
              if (obj instanceof FileNode)
                   return (FileNode)obj;
              else
                   return null;
           class DirExpansionListener implements TreeExpansionListener {
            public void treeExpanded(TreeExpansionEvent event) {
                final DefaultMutableTreeNode node = getTreeNode(
                    event.getPath());
                final FileNode fnode = getFileNode(node);
                Thread runner = new Thread() {
                        public void run() {
                             if (fnode != null && fnode.expand(node)) {
                                  Runnable runnable = new Runnable() {
                                       public void run() {
                                            m_model.reload(node);
                                  SwingUtilities.invokeLater(runnable);
                runner.start();
            public void treeCollapsed(TreeExpansionEvent event) {}
         class DirSelectionListener
              implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent event) {
                   DefaultMutableTreeNode node = getTreeNode(
                        event.getPath());
                   FileNode fnode = getFileNode(node);
                   if (fnode != null)
                        m_display.setText(fnode.getFile().
                             getAbsolutePath());
                   else
                        m_display.setText("");
         public static void main(String argv[]) {
              JFrame frame= new JFrame( "FileSystem Viewer");
              DirTree dir = new DirTree();
              frame.getContentPane().add(dir);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    class IconCellRenderer
         extends    DefaultTreeCellRenderer {
         public IconCellRenderer() {
              setLeafIcon(null);
              setOpenIcon(null);
         public Component getTreeCellRendererComponent(JTree tree,
              Object value, boolean sel, boolean expanded, boolean leaf,
              int row, boolean hasFocus) {
              // Invoke default implementation
              Component result = super.getTreeCellRendererComponent(tree,
                   value, sel, expanded, leaf, row, hasFocus);
              DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode)value;
              Object obj = node.getUserObject();
              setText(obj.toString());
            if (obj instanceof Boolean)
                   setText("Retrieving data...");
              if (obj instanceof IconData) {
                   IconData idata = (IconData)obj;
                   if (expanded)
                        setIcon(idata.getExpandedIcon());
                   else
                        setIcon(idata.getIcon());
              else
                   setIcon(null);
              return result;
    class IconData {
         protected Icon   m_icon;
         protected Icon   m_expandedIcon;
         protected Object m_data;
         public IconData(Icon icon, Object data) {
              m_icon = icon;
              m_expandedIcon = null;
              m_data = data;
         public IconData(Icon icon, Icon expandedIcon, Object data) {
              m_icon = icon;
              m_expandedIcon = expandedIcon;
              m_data = data;
         public Icon getIcon() {
              return m_icon;
         public Icon getExpandedIcon() {
              return m_expandedIcon!=null ? m_expandedIcon : m_icon;
         public Object getObject() {
              return m_data;
         public String toString() {
              return m_data.toString();
    class FileNode {
         protected File m_file;
         public FileNode(File file) {
              m_file = file;
         public File getFile() {
              return m_file;
         public String toString() {
              return m_file.getName().length() > 0 ? m_file.getName() :
                   m_file.getPath();
         // Alternatively we copud sub-class TreeNode
         public boolean expand(DefaultMutableTreeNode parent) {
              DefaultMutableTreeNode flag =
                   (DefaultMutableTreeNode)parent.getFirstChild();
              if (flag==null)       // No flag
                   return false;
              Object obj = flag.getUserObject();
              if (!(obj instanceof Boolean))
                   return false;      // Already expanded
              parent.removeAllChildren();  // Remove Flag
              File[] files = listFiles();
              if (files == null)
                   return true;
              Vector v = new Vector();
              for (int k=0; k<files.length; k++) {
                   File f = files[k];
                   if (!(f.isDirectory()))
                        continue;
                   FileNode newNode = new FileNode(f);
                   boolean isAdded = false;
                   for (int i=0; i<v.size(); i++) {
                        FileNode nd = (FileNode)v.elementAt(i);
                        if (newNode.compareTo(nd) < 0) {
                             v.insertElementAt(newNode, i);
                             isAdded = true;
                             break;
                   if (!isAdded)
                        v.addElement(newNode);
              for (int i=0; i<v.size(); i++) {
                   FileNode nd = (FileNode)v.elementAt(i);
                   IconData idata = new IconData(DirTree.ICON_FOLDER,
                        DirTree.ICON_EXPANDEDFOLDER, nd);
                   DefaultMutableTreeNode node = new
                        DefaultMutableTreeNode(idata);
                   parent.add(node);
                   if (nd.hasSubDirs())
                        node.add(new DefaultMutableTreeNode(
                             new Boolean(true) ));
              return true;
         public boolean hasSubDirs() {
              File[] files = listFiles();
              if (files == null)
                   return false;
              for (int k=0; k<files.length; k++) {
                   if (files[k].isDirectory())
                        return true;
              return false;
         public int compareTo(FileNode toCompare) {
              return  m_file.getName().compareToIgnoreCase(
                   toCompare.m_file.getName() );
         protected File[] listFiles() {
              if (!m_file.isDirectory())
                   return null;
              try {
                   return m_file.listFiles();
              catch (Exception ex) {
                   JOptionPane.showMessageDialog(null,
                        "Error reading directory "+m_file.getAbsolutePath(),
                        DirTree.APP_NAME, JOptionPane.WARNING_MESSAGE);
                   return null;
    }

  • Including pictures in a jar file

    Hi all, I want to create a jar file where I include a couple of pictures...... I have succesfully included them into the archive but I have found that the coding I use cannot be sued within a .jar file and hence none of the pictures are loaded :( I'm using kit.getImage("imagename.gif") command to load the images..... this does howeevr not seem to work when using a .jar file....... anyone got anyideas of what code should go instead of the kit.getImage("imagename.gif") ?
    Thx
    Garaz

    I would reply to that but I'll just stick with what
    you gave me..... thx for replying anyway, at a first
    look it seems as if I didn't specify the search
    pattern anough to get a good score when seraching....
    well thx for replyingDon't take it personally, this question has just been answered many times lately. I didn't feel like doing it again.

  • Pics in a Jar File

    Hi everybody,
    if I display a picture in an applet running in a browser
    , then I use dataUrl to get the pictures without
    a security exception.
    My question is: Can I put the picture in a jar file,
    the same where the applet is, and then open the
    pictures with an ImageIcon object, without using
    dataURL ??
    thanx
    Stephan

    If the file is included in a jar, you have to access it this way:
    URL url=myApplet.class.getResource("MultiMedia/myPic.jpg");
    Image myImage=Toolkit.getDefaultToolkit().getImage(url);
    where:
    myApplet.class is the name of your applet class file
    MultiMedia/ is a sub-directory relative to the applet (if applicable_)
    myPic.jpg is the name of your image file.
    V.V.

  • How to retrieve resources from a jar file ?

    Hello,
    Currently, I have application classes in a jar file, and all other resources (pictures, properties, and so forth..) in my windows folder. I do not have any problem for using them such way. For example to set an icon to a JFrame I have coded :
    f.setIconImage("mypicture.jpg");To make installation easier, I'd like to put my picture into the jar file with the classes. Is it possible ? if so, how should I modify my code to make things work ? Should I specify a special path ?
    Thanks for all
    Gege

    Thanks a lot, I'm going to try both ways.What both ways? Both replies are about the same thing -- using the classpath to find resources.
    The question now is what about if there is the same file
    name in the jar file and also in the directory ? Is
    there a search hierarchy ?It will find the first one it encounters in the classpath. You shouldn't have 2 resources with the same name in the classpath -- that's just like having two classes with the same package and class name.

  • Read images from a jar file?

    Hello, I'm converting a 6i app to 10g. This app does a ton of read_image_file() calls to
    change GIF images on the screen based on user actions. In 6i the images are all stored on the local hard drive. The images are not icons for buttons, but images that appear in different locations on the screen.
    For 10g, is it possible to leave the images in a jar file and effectively read the images from that? Otherwise, I suppose I'm looking at using webutil functionality to download the jar file and unjar it into an images directory for reading from the client?
    Any best-practice scenario for this sort of thing?
    Thanks for any info,
    Gary

    We are migrating from 6i to 10g too. And I try to not use webutil. All my pictures (icons gif files) are in a jar file.
    Just make attention of the size of your pictures. The jar file is loaded when you launch the application (the first time, and after, only if the jar file has changed).

  • How does the app know image folder (non class files) wrapped in jar file?

    Hi,
    I created an jar file, client.jar, which wrap all necessary files, including packaged class files ( in a hierarachy structure), image folder, properties folder, and ext folder (containing other jar files used). When I run the jar file, like
    java -classpath c:\tmp\client.jar -jar client.jar
    the app does not know where the images go and could not get the properties files. Actually the image and properties files are contained in the same file: client.jar. How can I fix this. I don't want to extract the jar file back to several separated folders and then run it.
    Appreciate the help.

    Unfortunately you have to make some changes in your code.. to find the pictures you need to replace:
    ImageIcon pic = new ImageIcon("pic.gif");
    with
    URL url = MyClass.class.getResource("pic.gif");
    ImageIcon pic = new ImageIcon(url);
    where MyClass is the class which needs to load the resource.
    I hope this helped you! /Pingu

  • 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);

  • Using images stored in JAR files

    I've got a small program which displays an image in a frame. I packaged all my classes and the picture into a jar file and made it executable. I can get the application to run but the picture doesn't show up.
    Can i load the image whilst it is still in the jar file or do i have to extract it to use it? Please help...
    Frendy

    In your class you are loading an image correct? Here is some code to do it.
    try
    URL imageURL = getClass().getClassLoader().getResource( "image.gif" );
    if ( imageURL != null )
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image image = tk.createImage( ( ImageProducer ) imageURL.getContent() );
    catch ( Exception e )

  • Gif files placed in a jar file. Help to get these files.

    I have placed all the gif files in a jar file.
    added the gif.jar to the project in the required libraries of project properties.
    In the toolbar class I gave this.
    JButton btnNew = new JButton(new ImageIcon("new.gif"));
    and was expecting it to shpw the icon but I didn't get it?
    Can I place the gifs in a jar file.
    What else can I change/check to see the icons?
    Thanks.

    Ok, lets try it this way:
    I have small samples on my server, which solve your
    problem. If you look at them, you can see
    how it works from a working example as starting point.
    CAUTION: This one ONLY works, if you have
    selected a JVM 1.3x.
    [ It doesnt work for jvm 1.4, because it references
    the main class in unnamed space. Thanks SUN ! -
    why was this needed ??? (security I guess) ]
    Steps:
    1) goto http://www.snowraver.org/java/index.htm
    2) download the "jarcreator.jar" example
    [ There is a small link "Download JarCreator.jar -
    although you also can start it as WebStart application
    if you click on the big button on that homepage ]
    3)
    The jar file contains the classes as well as the
    java source files and 2 gif pictures, which are
    loaded using the above explained method
    "LoadImageIcon"
    You can see how it works from that example.
    For extracting the source files, you can rename it
    and give it the ending .zip on windows, then
    you can extract all files using WinZip )
    The main class (called Idefix above) must be outside
    any package, that is, there must not be
    a package statement at the beginning.
    Some notes:
    If you are working without jar file, the method
    can return an ImageIcon object, although it
    couldnt find it. In this case, the width and length
    of that ImageIcon are zero.
    Usually no problem. But imagine you use the
    image icon for a tiled background. You loop
    would be endless then.
    It's a good idea to inspect the width of an imageicon
    for checking its greater zero.

  • How do you convert a jar file into a java file,  ?

    how do you convert a jar file into a java file ?
    I am new to Java ,but have a little experience in C++ and Visual Basic.
    I want to edit and maybe create my own mobile games that are written or converted into jar files.
    At the moment I am using Java NetBeans , and Easy Java( the java pad).
    However the only solution I tried was to open the JAR file in winrar and see that its made up of png picture files,
    midi music files and class files. Unfortunately when I uncompressed the JAR file , there was NO java file to be seen and the JAVA editors Do not show the class file like a Java file. So why is there no extension Java file in the mobile JAR game ?

    801283 wrote:
    how do you convert a jar file into a java file ?You generally don't. There exist decompilers, but if you're meant to have the source, you should either have it because you are the author, or you should be able to get it from the author.
    I am new to Java ,but have a little experience in C++ and Visual Basic.Does that experience include turning .exe files into C++ code? Because that's the equivalent of what you're asking
    I want to edit and maybe create my own mobile games that are written or converted into jar files.Eh?
    Are you saying you want to take existing games and modify them? If the creators allow you to modify their source, then they'll provide you with that source (the .java files). If you're allowed to add things but not modify, you don't need .java files. Just documentation, which, again, the creators should be providing.
    Or are you saying you want to create your own games and distribute them in jar files? If so, there's no need to turn jars into .java.
    However the only solution I tried was to open the JAR file in winrar and see that its made up of png picture files,
    midi music files and class files. Unfortunately when I uncompressed the JAR file , there was NO java file to be seen and the JAVA editors Do not show the class file like a Java file. So why is there no extension Java file in the mobile JAR game ?Why would you expect there to be one?

  • Resources from JAR files

    This is doubtless very simple stuff, but I nonetheless cannot figure out where I?m going wrong. I just need to open up some image files as icons in my program, and I?m trying to put all of the classes and resources in one jar file. I?m loading the image using getResource, and I have the images in a folder in the same place as my classes. Everything works fine when the files are separate, and the images load successfully. But then I put all the files into a jar (preserving the same hierarchy) and suddenly getResource returns NULL and of course the pictures don?t load. Is there anything else I ought to be doing?
    Many thanks,
    Ned

    Do any other ideas occur to anyone?Clearly there's a mismatch between the path used to reference the images, and the path where they live. This is pretty standard code, I've used it dozens of times, and I'm sure that the other responders have as well. On the surface, what you're doing looks right, so that only leaves one possibility.
    Two, actually: you aren't by any chance running this in an app-server or web-server?
    Assuming you aren't, put some debugging statements in, like this (not compiled, and I can't remember your image paths):
        URL resourceUril = this.getClass().getResource("/some/path/here");
        System.out.println("trying to load image from: " + resourceURL);This will print out a URL in the form jar:/some/path/here. Now display the contents of your jarfile, with jar tvf JARFILE. You'll see whether the path reported by the getResource() call is a valid path in your jarfile.

  • Unable to install jar files on nokia n82

    unable to install jar files on nokia n82 please help me ........... tell me hurry

    Hi wahab999
    In the case of mig33.jar if you have downloaded zip file to your PC, there are three versions included and you are presumably using the version below:
    mig33 V 3.02 Beta (signed) has the complete feature set (with profiles and picture sharing on the mobile). Generally this is compatible with phones that are Java MIDP 2.0 and above. This version is signed as a trusted application and some mobile phones prefer this version.
    Firstly go to Application Manager > Options > Settings and set "Online Certificate check" = OFF and Software Installation = ALL
    I hope that changing Software installation = ALL may help you with this issue.
    Happy to have helped forum in a small way with a Support Ratio = 37.0

  • Cant use jar file - JAVA -

    - JAVA -
    Basically I have few files in one package in every one of them I worte:
    "pack preyPackage;"
    And I have some .jar file that I try to use. So I drag it into the oracle compiler, but I still couldnt use it. But if I delete the row:
    "pack preyPackage;"
    from each .java I able to use that .jar file.
    my question is how can I still use that .jar file and package's all that other files..
    Picture that shows the problem:
    http://hwzone.co.il/community/index.php?action=dlattach;topic=290416.0;attach=92107;image
    Thanks.

    Tried it and get strange behaviours in JDev 10.1.3.3...
    The latest version with sources can be found at
    http://stwww.weizmann.ac.il/G-CS/BENARI/oop/index.html
    You should get that one and modify the sources to include a package name.
    I have little time to do that because I'm going on holiday for a week...
    --olaf                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for