Ways to display images in applets

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.