The display of images in an Applet requires the introduction of the following packages and calls to the ImageObserver interface
import java.awt.image.*;
import java.awt.image.ImageObserver;
import java.net.URL;
public class MyApplet extends Applet implements ImageObserver {...
Two. Define the image Path
URL Imgurl = Getdocumentbase ();
Set the path to be the same as your HTML file.
URL Imgurl = Getclassbase ();
Set the path to be the same as your HTML file.
Three. Get image
img = getImage (imgurl,imgname);
Of course, you might want to put your image file in a directory, so you can do it
img = getImage (imgurl, "img" + imgname);
Four. Display image
The most basic method is to invoke DrawImage (), which is defined in the graphics class, and the simplest invocation form is as follows:
G.drawimage (image, XPosition, yposition, this);
The last parameter called ImageObserver.
Five. The final supplement
The above is the most basic, of course, sometimes you even want to make your image file into a jar package, then you need to use
getResourceAsStream () method.
InputStream in = getClass().getResourceAsStream("image.gif");
byte buffer[] = new byte[in.available()];
for (int i = 0; n = in.available(); i < n; i ++)
buffer[i] = (byte)in.read();
Image img = createImage(buffer);
Six. A complete small example
import java.awt.*;
import java.applet.*;
import java.awt.image.*;
import java.awt.image.ImageObserver;
import java.net.URL;
//使用ImageObserver接口
public class MyApplet extends Applet implements ImageObserver{
Image img;
String imgPath = "";
int xpoint = 100, ypoint = 100;
public void init() {
setBackground(Color.white); //设置背景色
setForeground(Color.blue); //设置前景色
imgPath = "img/" + "test.gif"; //设置图象文件路径
}
public void paint(Graphics g) {
URL imgURL = getDocumentBase();
img = getImage(imgURL, imgPath);