Home » Core Java » applet » Draw Image in Applet

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of