简体   繁体   中英

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);

这应该可以解决问题(如果从从同一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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM