在Applet中显示图片

来源:互联网 发布:上海勇进软件徐州 编辑:程序博客网 时间:2024/04/26 11:54

//DisplayImage.java
//显示图片,在Graphics类drawImage方法可显示图像,但需要Image对象作参数
//Applet类 getImage方法可得Image对象,但需URL对象作参数。
//drawImage(Image对象<======getImage(URL对象<=======URL类))

//在D:/java/下有displayImage图片,没有可变更路径。


//<applet code=DisplayImage width=600 height=700>
//</applet>


import java.awt.*;
import java.applet.*;
import java.net.*;
import java.applet.Applet;

public class DisplayImage extends Applet
{
 public void paint(Graphics g)
 { 
  try
  {
   URL pairURL=new URL("file:/d:/java/displayimage.jpg");//注意URL的写法。
   Image myImage=getImage(pairURL);
   int w=myImage.getWidth(this);
   //获取图片宽度,这个this不了解?ImageObserve 应该是一个通知类接口啊,
   //为什么要用this呢?

   int h=myImage.getHeight(this);//获取图片高度。
   g.drawString("The width of the image is= "+w+"The height is= "+h,10,15);
   g.drawString("get File= "+pairURL.getFile(),10,30);//得到URL的地址。
   g.drawImage(myImage,w,h,this);   //this<===ImageObserve  ????
  }
  catch (MalformedURLException e)
  {
   g.drawString("Image not found",30,30);
  }

 }
}