9

Java - How to access a packaged image in an applet pot

 3 years ago
source link: https://www.codesd.com/item/java-how-to-access-a-packaged-image-in-an-applet-pot.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Java - How to access a packaged image in an applet pot

advertisements

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


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)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK