如何在 Java 小程序中显示位图图像? [英] How can I display a bitmap image in a Java applet?

查看:30
本文介绍了如何在 Java 小程序中显示位图图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何在 Java 小程序中显示图像(或 ImageIcon).以下是我的代码.图片 (test.bmp) 确实存在并且在 D 驱动器上,但是当我运行它时,我得到了一个没有任何内容的小程序窗口.有人能告诉我让 ImageIcon 显示我缺少什么吗?

I am having a hard time figuring out how to show an Image (or ImageIcon) in a Java applet. The following is my code. The picture (test.bmp) does exist and is on the D drive but when I run this I get the applet window with nothing in it. Can somebody tell me what I am missing to make the ImageIcon show?

public class Form1 extends JApplet {
    ImageIcon i;

    public void init(){
        i = new ImageIcon("D:\test.bmp");
    }

    public void paint(Graphics g){
        i.paintIcon(this, g, 0, 0);
    }
}

谢谢,史蒂夫.

推荐答案

当您从服务器运行小程序时,通过绝对本地文件路径引用您的图像可能不起作用.使用 ImageIcon(URL 位置)构造函数并 让 URL 指向服务器上的图像资源.使用 JApplet.getCodeBase() 确定您的小程序的来源并将文件名附加到它.

Referencing your image through an absolute local file path might not work when you run your applet from a server. Use the ImageIcon (URL location) constructor and Have the URL point to the image resource on the server. Use the JApplet.getCodeBase() to determine where your applet originates and append the file name to it.

public class Form1 extends JApplet {
    Image i;

    public void init() {
        try {
            i = ImageIO.read(new URL(getCodeBase(), "test.bmp"));
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        g.drawImage(i, 0, 0, null);
    }
}

ImageIO 支持 BMP,更改后的示例适用于我.

ImageIO supports BMP and the changed sample works for me.

编辑 2:如果它仍然不显示图像,请尝试../test.bmp",因为当您从 Eclipse 运行小程序时,它具有 bin 目录作为代码库.

Edit 2: If it still doesn't display the image, try "../test.bmp" because when you run an applet from lets say Eclipse it has the bin directory as the codebase.

编辑 3:如果将 test.bmp 放入 jar 或类路径中,则可以使用相同的方式加载它,但要替换

Edit 3: If you put your test.bmp into the jar or on the classpath, you can load it using the same way but replacing

new URL(getCodeBase(), "test.bmp")

Form1.class.getResource("test.bmp")

这篇关于如何在 Java 小程序中显示位图图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆