Loading images inside applet JAR

Hi
This is my issue: I have an applet which contains images inside the applet JAR. I want to display these images in my applet, but apparently due to browser access restrictions, I'm not allowed.
My first code was like this:
//security restrictions on browsers do not allow getResource
ImageIO.read(MyClass.class.getResource("imgs/img.png"));
//getResourceAsStream should be allowed by browsers
ImageIO.read(MyClass.class.getResourceAsStream("imgs/img.png"));Both lines work when I execute the applet locally (command line / programming IDE), but when I deploy it to my web server, the resource "imgs/img.png" becomes a relative URL to my web application context (like /webcontext/MyClass/imgs/img.png). It works locally because the call to getResource returns a URL object with "file:" protocol, but I need it to look for my images bundled inside the JAR, not web hosted images.
I need to avoid making the applet look for these images as a web resource... how can I do it?
Thanks!

dev@java wrote:
warnerja wrote:
I'm not convinced the code you posted wouldn't work, but since this is an applet, you have access to the Applet class. Check out the Applet.getImage method in conjunction with Applet.getCodeBase.
[http://java.sun.com/javase/6/docs/api/java/applet/Applet.html]
getCodeBase returns my web context, like http://myhost.com/mycontext/ , so it is pretty much the same as above.
Thanks for your replyThat is the way to load resources though. Hence back to my earlier statement about not being convinced it would not work, with this addition: It should work, assuming you actually do have the resources properly located with the web app, whether they be in a jar, or loose files relative to where the web app is. My guess at this point is that they are not.

Similar Messages

  • 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 Images into Applets

    I've been having problems loading an image into an Applet. I've found that when the getImage() call is put into the init() method it loads the image fine, also implementing an imageUpdate call. However, now I'm trying to expand on this by putting it into a button click, it hangs indefinitely while waiting for the image to load.
    Another interesting point I've noticed is that the Canvas subclass ImageSegmentSelector uses a PixelGrabber in its constructor to put the Image into a buffer - when this class is created from the imageUpdate() call, NOT the init() call, the grabPixels() call hangs indefinitely too!!
    Any feedback, please,
    Jonathan Pendrous
    import java.applet.*;
    import java.net.*;
    import jmpendrous.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class XplaneGlobalSceneryDownloader extends Applet implements ActionListener{
    ImageSegmentSelector worldMap;
    Image img;
    URL url;
    int longtitude = 36;
    int latitude = 18;
    boolean imageLoaded;
    TextField t1, t2,t3;
    Label l1,l2,l3;
    Button b1;
    Applet a1;
    public void init() {
    a1 = this;
    l1 = (Label) add(new Label("Number of horizontal sections: "));
    t1 = (TextField) add(new TextField("45",3));
    l2 = (Label) add(new Label("Number of vertical sections: "));
    t2 = (TextField) add(new TextField("45",3));
    l3 = (Label) add(new Label("URL of image file: "));
    t3 = (TextField) add(new TextField("file:///C:/java/work/xplane_project/source/world-landuse.GIF",60));
    b1 = (Button) add(new Button("Load image"));
    b1.addActionListener(this);
    validate();
    // THIS CODE WORKS FINE ...
    /*try { url = new URL("file:///C:/java/work/xplane_project/source/world-landuse.GIF"); }
    catch(MalformedURLException e) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false) { try { Thread.sleep(1000);   } catch(InterruptedException e) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();*/
    //repaint();
    //worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    //repaint();
    public void actionPerformed(ActionEvent e) {
    try { longtitude = Integer.parseInt(t1.getText()); } catch (NumberFormatException ex) {System.exit(0); }
    try { latitude = Integer.parseInt(t2.getText()); } catch (NumberFormatException e2) {System.exit(0); }
    try { url = new URL(t3.getText()); }
    catch(MalformedURLException e3) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false)
    { try { Thread.sleep(1000);   } //KEEPS ON LOOPING
    catch(InterruptedException e4) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(a1, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();
    public boolean imageUpdate(Image i, int flags, int x, int y, int w, int h){
    // THIS NEVER GETS CALLED AT ALL //
    if (((flags & ImageObserver.WIDTH) != 0) && ((flags & ImageObserver.HEIGHT) != 0)) {
    //worldMap = new ImageSegmentSelector(this, i, longtitude, latitude);
    //add(worldMap);
    //validate();
    //repaint();
    imageLoaded = true;
    return false;
    return true;
    }

    Sorry, thought this had been lost.
    You can load a file if the applet itself is run from the local filesystem - it loads it fine from the init(), but not otherwise. But I haven't got the applet to run from a browser yet without crashing (it's OK in the IDE debugger), so that's the next step.

  • Loading Images in Applets

    Is it possible to use the Toolkit class to load images in "unsigned" applets. I tried that but it throws a security exception:
    com.ms.security.SecurityExceptionEx[MyApplet.init]: cannot access file http://localhost/MyApplet/images/Image1.gif
    Though I am reading the image from the server not the client machine.
    Any help would be appreciated.
    Thanks in advance,
    Samer Meqdad

    Here's the code:
    Image img;
    img = Toolkit.getDefaultToolkit ().getImage (getCodeBase() +  "images/MyImage.gif");The exception thrown is:
    com.ms.security.SecurityExceptionEx[Host]: java.io.IOException: bad path: C:\Documents and Settings\samerm\Desktop\file:\C:\MyApplet\images\MyImage.gif
         at com/ms/security/permissions/FileIOPermission.check (FileIOPermission.java)
         at com/ms/security/PolicyEngine.deepCheck (PolicyEngine.java)
         at com/ms/security/PolicyEngine.checkPermission (PolicyEngine.java)
         at com/ms/security/StandardSecurityManager.chk (StandardSecurityManager.java)
         at com/ms/security/StandardSecurityManager.checkRead (StandardSecurityManager.java)
         at com/ms/awt/WToolkit.getImageFromHash (WToolkit.java)
         at com/ms/awt/WToolkit.getImage (WToolkit.java)
         at DiamondsApplet.init (DiamondsApplet.java:54)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)

  • Best place to load Images in applet game

    Sorry for the double post but I just realised I originally posted this in completely the wrong forum!
    Hello,
    I have made a fairly basic game of 21/BlackJack and was wondering where the best place to load the card Images is/was...
    Currently I am loading the images into an Image[ ] in the applet class, but was thinking maybe the loading should be done in the deck or card class?
    In the applet class I use an ordered version of the deck to assign the cards in the image[ ], then to call an image I generate an index number based on the current cards value and suit....
    However this method means I have to create an instance of the deck in the main program, whereas before I had it as a private member of the dealer class, so only the dealer could access it (which seems "safer", no?)
    So would a better idea be to have a loadImage() method in the deck class, which populates an Image[ ] with the cards and pass this to the main program?
    Thanks

    Ken,
    Loading images is slow so you only want to do it once... maybe when you generate the deck ... and "image" is definately an attribute of the card, yes... I'd actually implement the loadImage() as a method in the card class so set a private image variable... and then get the the dealer to call the loadImage method for each card as "he" builds the deck.
    But that's just how I would do it... and I'm no guru so don't take it as gospel... I'd be surprised if there wasn't atleast one "purer" way of doing it.

  • How do I position a Loader image inside a Sprite?

    In AS3 / CS4 I'm trying to programmatically create a bunch of rectangular objects, let's call them 'cards', that will contain an image and a colored background and eventually some other elements like text.  I want to create alot of these cards and move them around inside of a larger panel (also a Sprite) of sorts.  I can successfully create colored rectangles in my cards and place the cards where I want in the panel, but whenever I try to add an image to a card, I can't seem to position the image inside the card's coordinate space, it ends up being placed inside the larger panel's coordinate space instead, even though I'm adding the image/loader as a child of the card.  I thought maybe it had something to do with having to wait until the image loading was complete, so I added the listener as a test but that didn't work.  Here's the code:
                var cont:Sprite = new Sprite();  containing 'card'
                var rect:Sprite = new Sprite();  // draw a colored rectangle in the card
                var loader:Loader = new Loader();
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, positionLoader);
                rect.graphics.beginFill(0xbb3399);
                rect.graphics.drawRect(60,60,99,99);  // this works as expected
                rect.graphics.endFill();
                cont.addChild(rect);
                addChild(cont);
                var req:URLRequest = new URLRequest("top.png");
                loader.load(req);
                function positionLoader(e:Event):void {
                    loader.x = 30;  // position the image inside the containing card
                    loader.y = 30;
                    cont.addChild(loader);  // add the image to the card

    I solved this problem.

  • Need help with loading images in executable Jar

    Hi,
    I've developed an application using netbeans that needs to load and display images.
    I use netbeans Clean and Build function to create an executable Jar file. When I run the executable Jar file it runs fine but when I come to a section of the application that needs images it freezes and can't load the images.
    When I then return to netbeans the part of the program that did successfully run before Clean and Build doesn't work anymore and I get an error message saying Uncaught error fetching image:
    I use,
    URL url = getClass().getResource("images/image1.png");
    Image image1 = Toolkit.getDefaultToolkit().getImage(url);to load an image.
    Can someone tell me why, when I clean and build my project to create a JAR, my images fail to load.
    Should I be storing the images in a specific folder or something??
    Thanks

    I've opened the JAR using winzip and, for some reason, the JAR hasn't preserved my file structure. So, when I try to look for an image as follows:
    URL url = getClass().getResource("images/file1.png");
    Image img= Toolkit.getDefaultToolkit().getImage(url);The folder doesn't exist and so it can't find the image.
    Can someone tell me how to keep my file structure when I create the JAR or an alternative way to find the images within the JAR file.
    Cheers

  • Loading images inside the package structure

    i am having trouble loading images that are imbedded into the package structure. I am assuming this is possible(99.9% sure)
    the classes are
    cardgameframework/CardGame.class
    cardgameframework/cardsupport/Card.class
    cardgameframework/cardsupport/images/2D.GIF
    cardgameframework/cardsupport/images/2C.GIF
    how do i load 2D.gif and 2C.gif from CardGame
    i tried
    Image i = Toolkit.getDefaultToolkit.getImage(
    "/cardgameframe/cardsupport/images/2C.GIF");
    and
    Image i = Toolkit.getDefaultToolkit.getImage(getClass().getResource(
    "/cardgameframe/cardsupport/images/2C.GIF"));
    but neither of these seem 2 work
    any help would be appreciated

    My initial thought is that you've got the package wrong in your two examples - you've got cardgameframe and not cardgameframework.
    Anyway, I tend to use the latter of your approaches - getClass().getResource("/cardgameframework/cardsupport/images/2D.GIF").
    Be careful of case in your URLs.
    Note that if getResource can't find your file it will return null - ensure that you're getting back a non-null URL:
    URL url = getClass().getResource("/cardgameframework/cardsupport/images/2D.GIF");
    System.out.println("URL: " + url);
    ...If your URL is non-null then the problem will be with the format of your image file (if it is null then you'll get a NullPointerException eventually).
    Hope this helps.

  • URLClassLoader - loading classes inside of JAR archives

    Hi. I'm trying to load get an instance of a class inside of a JAR file. I have:
              try
                   URLClassLoader urlcl = new URLClassLoader(new URL[] { new URL("file://C:/Documents and Settings/Owner/My Documents/Eclipse Java IDE Work/temp/test.jar") });
                   Applet clientClass = (Applet)urlcl.loadClass("myclass").newInstance();
                   clientClass.setStub(new ClientStub());
              catch(Exception e) { e.printStackTrace(); }Problem is, everytime I try to run it, I get:
    java.lang.ClassNotFoundException: client
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)Any suggestions?
    And yes, I can extract and view the file manually. Thanks.

    new File("C:/Documents and Settings/Owner/My Documents/Eclipse Java IDE Work/temp/test.jar").toURL()?Then I have to conclude the JAR file is wrong. Can you show the relevant part of jar tvf test.jar?

  • 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

  • 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.......

  • Problem with loading image to Applet.

    Hello. Im preety new to Java, and currently ive got problems with adding an image to my applet. I tried to make game, similar to Mario - a platform based one. I found a source code of something close to that, and wanted to test but i couldnt get images loading. Here's the code :
    Main class :
    package pl.wat.edu;
    import java.applet.*;
    import java.awt.*;
    public class Main extends Applet implements Runnable{
         Thread th;
         private final int speed = 15;
         private Level obecny_poziom;
         private Image dbImage;
         private Graphics dbg;
         MediaTracker mt = new MediaTracker(this);
         private Image ziemia1;
         @Override
         public void destroy() {
              // TODO Auto-generated method stub
              super.destroy();
         @Override
         public void init() {
              // TODO Auto-generated method stub
              super.init();
              setSize(stale.wielkosc_apletu_szerokosc, stale.wielkosc_apletu_wysokosc);
              //setBackground(Color.blue);
              //ziemia1 = getImage(getCodeBase(), "g1.GIF");
              obecny_poziom = new Pierwszy(this, this);
         @Override
         public void start() {
              // TODO Auto-generated method stub
              super.start();
              // create new thread
              th = new Thread (this);
              // start thread
              th.start ();
         @Override
         public void stop() {
              // TODO Auto-generated method stub
              super.stop();
              // Thread stop
              th.stop();
              th = null;
         public void run() {
              // TODO Auto-generated method stub
              while (true){
                   repaint();
                   try
                        Thread.sleep(speed);
                   catch (InterruptedException ex)
                   // do nothing
         @Override
         public void paint(Graphics arg0) {
              // TODO Auto-generated method stub
              super.paint(arg0);
              //arg0.drawImage(ziemia1,10,10,this);
              obecny_poziom.paintLevel(arg0);
         public void update (Graphics g)
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint(dbg);
              g.drawImage (dbImage, 0, 0, this);
    }and Level class that have draw levels from String rows :
    package pl.wat.edu;
    import java.applet.Applet;
    import java.awt.*;
    public abstract class Level {
         //private LevelElement [] elements;
         private WorldTile [] tiles;
         private WorldTile[][] tablica_kolizji;
         private Color [] colors;
         private Component parent;
         private int lewa_granica;
         private int prawa_granica;
         private int dlugosclevelu;
         private Image ziemia = null;
         private Image titi;
         private Applet applet;
         public abstract void resetLevel();
         public Level(Component parent, Applet applet) {
              super();
              this.parent = parent;
              this.applet = applet;
              ziemia = applet.getImage(applet.getCodeBase(), "g1.GIF");
         public void initializeLevel(String [] definitions){
              tablica_kolizji = new WorldTile [stale.dlugosclevela] [definitions[0].length()];
              lewa_granica = 0;
              prawa_granica = stale.wielkosc_apletu_szerokosc;
              int licznik_kratek = 0;
              for(int i=0; i<definitions.length; i++){
                   char [] definition_line = definitions.toCharArray();
                   for(int j=0; j<definition_line.length; j++){
                        if (definition_line[j] == ':')
                             tablica_kolizji[i][j] = null;
                        else if (definition_line[j]== 'g'){
                             Ziemia tile = new Ziemia(j*stale.szerokoscTile, i*stale.wysokoscTile, stale.ziemia_id, ziemia, parent);
                             tablica_kolizji[i][j] = tile;
                             licznik_kratek = 0;
              tiles = new WorldTile [licznik_kratek];
              int licznik = 0;
              for (int i = 0; i<tablica_kolizji.length; i++){
                   for(int j=0; j>tablica_kolizji[i].length; j++){
                        if (tablica_kolizji[i][j] != null){
                             tiles[licznik] = tablica_kolizji[i][j];
                             licznik++;
         public void paintLevel(Graphics g)
              try
                   // draw background
                   // draw all elements in elements array
                   for(int i=0; i<tiles.length; i++)
                        tiles[i].rysujTile(g);
              catch(Exception ex)
                   // do nothing
    Any ideas why this Image doesnt show up ?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    michali7x4s1 wrote:
    Thats a code i found somewhere, tried to check how some things work.Have you used exceptions before? If not, please read the sun tutorial on them as they are very very important. Also, whether this is your code or someone else's doesn't matter as it's yours now, and you would be best served by never throwing out exceptions as is done in this code. It's like driving with a blindfold on and then wondering why you struck the tree. It's always best to go through the tutorials to understand code before using it. If it were my project, I'd do it in Swing, not AWT. Fortunately Sun has a great tutorial on how to code in Swing, and I suggest you head there as well. Best of luck.

  • Loading Image outside the jar

    I have a .jar program that saves and loads imagens from a folder outside the jar. In my directory I have:
    myProg.jar
    images(folder)
    This is the way myProg.jar saves the images:
    BufferedImage myImage; //myImage is initialized somewhere else
    File file = new File("images/Pic"+temp+".jpg");
        try{
        ImageIO.write(myImage, "jpg", file);
           }catch(IOException io){}
    }catch(AWTException ea){}When I check the image is saved in my folder "images"
    Then, the prog tries to load the images this way:
    URL url = getClass().getResource("/images/"+name+".jpg");
    ImageIcon icon;
             if (url != null) {
                  icon = new ImageIcon(url);
                  picture.setIcon(icon);
             else {
                  url = getClass().getResource("/images/street.jpg");
                  icon = new ImageIcon(url);
                  picture.setIcon(icon);
             }Here I have an exception : Exception in thread "AWT-EventQueued-0" java.lang.NullPointerException
    I checked the url and it�s ok.
    Hope someone help.

    Well, I modified the getJarPath method to this:
    String getJarPath1(){
              String path=System.getProperty("java.class.path");
              for(int i=0;i<=path.length()-1;i++)
                   if(path.charAt(i)==';'){
                        return path.substring(0,i);
              return "";
         }Now I got the path I really need, for example:
    C:\Program Files\Eclipse\Workspace\myProject\images\pic.jpg
    Though, the picture is not loading. Here is what I am doing:
    String path=getJarPath1()+"\\images\\" + name + ".jpg";
    //path=C:\Program Files\Eclipse\Workspace\myProject\images\pic.jpg -> correct path
    URL u=null;
    try{
                 u = new URL(path);   //u is always null! why?
                }catch(MalformedURLException mf){}
    if(u!=null)
             try{
             icon = new ImageIcon(u);
             picture.setIcon(icon);
             }catch(Exception bla){}
             else {
             }What�s happening is that my "path" got the correct path, but when I put it in the URL it�s becoming null.
    The picture and the folder are in the correct place.
    I hope someone helps. Thx!

  • 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

  • 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

Maybe you are looking for

  • Error while filling the set up table for 2LIS_11_VAITM

    Dear Experts, i am facing an error while filling the set up table for 2LIS_11_VAITM in the source system. The error was "Company code for sales org 9000 does not exist (document 1326)". when i checked the document in the Header table VBAK,company cod

  • Photoshop CS6 is not recognizing the raw file from the Nikon D4S.

    Just picked up the Nikon D4S, took some shots to get acclimated and glad I did. When I uploaded them my PS program is telling me, "Camera Raw cannot open this file."  Than when I tried to edit an older image from my Nikon D300S I was getting the same

  • Cant change profile icon to photo

    Keeps askin if I want to save or share when I press to add photo

  • Drag and drop multiple mail messages into finder

    I am trying to move multiple mail messages into finder folders for organization and filing purposes.  I know it will save these as mail files but that is what I would like anyway.  It lets me drag and drop one message at a time but does not let me do

  • OpenAMF/Flex Resources

    I'm having a difficult time connecting to an OpenAMF service via Flex Remoting. I can do it fine in Flash but am having problems in Flex. I've also been succesful using an amfphp service and Flex. But when I provide the service information for the Op