Problem with loading a PNG image in JApplet
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 he开发者_Python百科ight=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!
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));
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.
It might be simply because you cut your code when pasting but are you doing an invalidate of the view to make it repaint?
精彩评论