applet

Draw Image in Applet

With this example we are going to demonstrate how to draw an image in an Applet. A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment. In short, to draw an image in an Applet you should:

  • Create a class that extends the Applet, such as DrawImageInApplet class in the example.
  • Use init() API method of Applet. This method is called by the browser or applet viewer to inform this applet that it has been loaded into the system. In this method call the getImage(URL url, String name) API method of Applet to get an Image object that can then be painted on the screen.
  • In paint(Graphics g) method call drawImage(Image img, int x, int y, ImageObserver observer) API method of Graphics to draw as much of the specified image as is currently available.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

public class DrawImageInApplet extends Applet {
	
	private static final long serialVersionUID = 2530894095587089544L;
	
	private Image image;
	
	// Called by the browser or applet viewer to inform
	// this applet that it has been loaded into the system.
    public void init() {
    	
    	image = getImage(getDocumentBase(), "http://www.myserver.com/image.jpg");
    	
    }
    
    // Paints the container. This forwards the paint to any
    // lightweight components that are children of this container.
    public void paint(Graphics g) {
    	
    	// draws as much of the specified image as is currently available
    	g.drawImage(image, 0, 0, this);
    	
    }

}

 
This was an example of how to draw an image in an Applet in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button