Java教程-在Applet中显示图像

在Applet中显示图像
Applet主要用于游戏和动画。为此,需要显示图像。java.awt.Graphics类提供了一个名为drawImage()的方法来显示图像。
drawImage()方法的语法:
- public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):用于绘制指定的图像。
如何获取图像对象:
java.applet.Applet类提供了一个名为getImage()的方法,该方法返回Image对象。语法:
public Image getImage(URL u, String image){}
Applet类的其他必需方法来显示图像:
- public URL getDocumentBase():用于返回嵌入applet的文档的URL。
- public URL getCodeBase():用于返回基本URL。
在applet中显示图像的示例:
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
在上面的示例中,使用Graphics类的drawImage()方法来显示图像。drawImage()方法的第四个参数是ImageObserver对象。Component类实现了ImageObserver接口。因此,当前类对象也将被视为ImageObserver,因为Applet类间接地扩展了Component类。
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>