开发者

Java - How to access an image packed in an applet jar

I have created an applet jar. That jar contains an images in the following folder

com\common\images\red.bmp

Now, I want to display this image on the Swing Applet.

private static final ImageIcon redIndicator = new ImageIcon("com\\common\\images\\red.bmp");

After that, I have attached the redIndicator to a JPanel but I am not able to see this image.

Any suggestions?

==================================EDITED=========================================

private static final ImageIcon marker = loadImage("com/common/images/scale.jpg");

@SuppressWarnings("unused")
private static ImageIcon loadImage(String imagePath) {

    BufferedInputStream imgStream = new BufferedInputStream(TpcHandler.class.getResourceAsStream(imagePath));
    int count = 0;

    if (imgStream != null) {

        byte buf[] = new byte[2400];

        try {
            count = imgStream.read(buf);
        } catch (java.io.IOException ioe) {
            return null;
        } finally {
            if (imgStream != null)
                try {
                    imgStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        if (count <= 0) {
            LOGGER.warning("Empty image file: " + imagePath);
开发者_运维知识库            return null;
        }

        return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
    } else {
        LOGGER.warning("Couldn't find image file: " + imagePath);
        return null;
    }
}

I am getting the following exception

java.io.IOException: Stream closed

at line count = imgStream.read(buf);


This should do the trick (if called from a class loaded from that same jar):

new ImageIcon(getClass().getResource("/com/common/images/red.bmp"))


Use YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"), read the stream to a byte[] and construct the ImageIcon based on that. (and don't use bmps - prefer png or jpeg)


Applets and Images that is a frequently asked questions so, as for Java applets and images, I recommend you read one of my previous answers hope it helps a bit :)

Good luck

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜