【问题标题】:Java - How to access an image packed in an applet jarJava - 如何访问打包在 applet jar 中的图像
【发布时间】:2011-12-03 23:37:30
【问题描述】:

我创建了一个applet jar。该 jar 包含以下文件夹中的图像

com\common\images\red.bmp

现在,我想在 Swing Applet 上显示此图像。

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

之后,我已将 redIndicator 附加到 JPanel,但我无法看到此图像。

有什么建议吗?

===================================已编辑============ ==============================

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

我收到以下异常

java.io.IOException: Stream closed

在线count = imgStream.read(buf);

【问题讨论】:

  • Jar 中路径的部分由“/”分隔,而不是“\”(在每个操作系统上)。

标签: java jar applet


【解决方案1】:

这应该可以解决问题(如果从同一个 jar 加载的类调用):

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

【讨论】:

    【解决方案2】:

    使用YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"),将流读取到byte[],并在此基础上构造ImageIcon。 (不要使用 bmps - 更喜欢 png 或 jpeg)

    【讨论】:

      【解决方案3】:

      小程序和图像是一个常见问题,所以对于 Java 小程序和图像,我建议您阅读one of my previous answers,希望对您有所帮助:)

      祝你好运

      【讨论】:

        猜你喜欢
        • 2019-12-16
        • 2011-01-23
        • 2012-02-21
        • 2017-12-10
        • 1970-01-01
        • 2012-01-21
        • 2014-07-05
        • 2013-07-25
        • 1970-01-01
        相关资源
        最近更新 更多