problem loading image from jar with an applet

Hi,
I’ve packaged my applet and all the iamges into a jar file for neatness. However the applet seems to be trying to load the images from outside of the jar rather than inside. meaning that I need to send the images in a folder seperately. Its messy! What am I doing wrong? Heres an example of where I am loading images in my code…


fileName = getClass().getResource("resources/terrain/grass.gif");
GRASS_TILE = Toolkit.getDefaultToolkit().getImage(fileName); 
mediaTracker.addImage(GRASS_TILE, 0);


I’ve tried using getCodeBase()+fileName and it doesnt make a difference!! How do I make it use the images in the jar!! lol. Thanks for any help.

Here is what I do… and in no should you think that what I do correct :wink:


 // use getResource so it works in jar files        
        URL iconUrl[] = new URL[6];                     
        iconUrl[0] = Client.class.getResource("images/blue.gif");                
        iconUrl[1] = Client.class.getResource("images/red.gif");
        iconUrl[2] = Client.class.getResource("images/green.gif");      
        iconUrl[3] = Client.class.getResource("images/yellow.gif");  
        iconUrl[4] = Client.class.getResource("images/magenta.gif");
        iconUrl[5] = Client.class.getResource("images/cyan.gif");
        
        // import the images, initialize pics of players &
        // initialize the score of every player to 0            
        ImageIcon gif[] = new ImageIcon[6];     
            for (int i = 0; i < 6; i++) {           
              if (iconUrl[i] != null)
                    gif[i] = new ImageIcon(iconUrl[i]);                           
              pic[i] = new JLabel(gif[i]);                                                        
            scores[i] = new JTextField("  0  ",5);
            scores[i].setBackground(Color.black);
            scores[i].setBorder(BorderFactory.createEmptyBorder());
            scores[i].setEnabled(false);
        }


might be hard to understand sorry.

If that does not work go to
http://developer.java.sun.com/developer/qow/archive/76/index.html

good luck


class ... extends Applet
[...]
URL keyboardImagePath;

keyboardImagePath=getClass().getResource("/gfx/keyboard.gif");
      
kb=getToolkit().getImage(keyboardImagePath);

that works for me.

btw u dont need an mediaTracker… the file is already loaded… if u try now to display it it will take awhile, cuz the image needs to be decrunched. and java waits with that task until it’s needed…

u can simply ask for one of the image properties like this:

kb.getWidth(null);

to start the decrunching procedure (as a side effect ;))

after that u can use it w/o any delay :slight_smile: