java显示位图,我怎样才能显示Java小程序的位图图像?

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

}

}

Thanks, Steve.

解决方案

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

}

}

Edit: ImageIO supports BMP and the changed sample works for me.

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.

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

with

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值