Article View: borland.public.jbuilder.java.swing
Article #9280Re: Loading images from jar file
From: nathanlaan
Date: Wed, 19 Apr 2000 00:00
Date: Wed, 19 Apr 2000 00:00
66 lines
2559 bytes
2559 bytes
> URL url =
>
ClassLoader.getSystemClassLoader().getResource("mypackage/smiley.jpg")
;
> file://System.out.println("url = " + url);
> if(url != null) {
> jframe.setIconImage(jframe.getToolkit().getImage(url));
> }
>
> One oddity, presumably to do with security...
> If I put the jpg file in the root of the jar file, it did not work.
> I had to put the jpg file in the same directory as the class that
was
> doing the resource loading (the mypackage subdirectory in this
case).
>
> Steve.
The getResource methods can only (as far aas I know) find resources at
the same package level as the class they are being loaded from.
here is code similar to the above code, only using a Stream to get the
file...
public static Image getImage( String name , Object object , Component
comp ) {
try {
// the image
Image img = null;
// the class to get the Image
InputStream is =
object.getClass().getResourceAsStream( name );
// the class to write out the Image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
int c;
// write out the Image file data
while( ( c = is.read() ) >= 0 )
baos.write(c);
// create the Image from the Image file data
img =
oolkit.getDefaultToolkit().createImage( baos.toByteArray() );
}
catch( IOException e ) {
}
// use the MediaTracker to load the Image
loadGraphics( img , comp );
return img;
}
catch( NullPointerException e ) {
System.out.println("Can't find: " + name);
return null;
}
}
public static void loadGraphics( Image image, Component comp ) {
MediaTracker tracker = new MediaTracker(comp);
if( image != null )
tracker.addImage( image , 0 );
try {
tracker.waitForAll();
}
catch( InterruptedException e ) {
}
}
Technical Details
Message-ID:
<38fe0585@dnews>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<38fd824d.4293483@newsgroups.borland.com> <38FDB38D.161605C7@cwcom.co.uk>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 111d45,ec9795bc13a1381d X-Google-Attributes: gid111d45,public From: "nathanlaan" <nlaan@ualberta.ca> Subject: Re: Loading images from jar file Date: 2000/04/19 Message-ID: <38fe0585@dnews> X-Deja-AN: 613260367 References: <38fd824d.4293483@newsgroups.borland.com> <38FDB38D.161605C7@cwcom.co.uk> X-Trace: 19 Apr 2000 12:14:13 -0800, 129.128.162.184 X-MSMail-Priority: Normal X-Priority: 3 Newsgroups: borland.public.jbuilder.java.swing X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2615.200