views:

99

answers:

2

Hi there,

I'm trying to load a PNG image from JAR file when running JApplet. The file is, I think, loaded properly - there are no errors. However it is not displayed. img.png is placed in the same directory as MainClass.java file. Here is the code:

InputStream imageURL = this.getClass().getResourceAsStream("img.png" );
byte[] bytes = null;
try {
    bytes = new byte[imageURL.available()];
    System.out.println(imageURL.available());
    imageURL.read(bytes);
}
catch(Exception e) {System.out.println("bleah");}

Image image = Toolkit.getDefaultToolkit().createImage(bytes);
Image imageScaled = image.getScaledInstance( 100, 150, Image.SCALE_SMOOTH );
jLabel6 = new javax.swing.JLabel( new ImageIcon( imageScaled) );`

and the HTML exerpt:

<APPLET codebase="classes" code="myapplet/MainClass.class" archive ="LittleApplet.jar" width=700 height=500></APPLET>

The image, as I wrote, is probably read, but not displayed in JLabel.

What am I missing/doing wrong?

Thanks in advance for the reply!

A: 

This works for me :

URL imageURL = this.getClass().getResource("img.png");
Image image = Toolkit.getDefaultToolkit().createImage(imageURL);
Image scaled = image.getScaledInstance(100, 150, Image.SCALE_SMOOTH);
JLabel label = new JLabel(new ImageIcon(scaled));
Valentin Rocher
A: 

Remove or comment out the line

System.out.println(imageURL.available());

Once you read from a stream, its going to be empty, its not a simple copy, reading from a stream is consuming the stream.

Also good practice to flush/close the stream once your done with it.

Knife-Action-Jesus