How To Display Image And Show Animation Using Applet In Java

In this article, we discuss how to display image and show animation using applet in java.

Introduction

 
In this article, we discuss how to display an image and show animation, using an Applet in Java.
 

Displaying Image in Java

 
Applets are widely used in animation and games.  For this, we require images to be displayed.
 
The Graphics class of Java, provides a drawImage() method to display an image.
 
Syntax
 
The syntax of the drawImage function to draw the specified image is:
 
public abstract boolean drawImage(Image image, int a, int b, ImageObserver observer)
 

Loading and Displaying Images

 
Images provide a way to augment the aesthetic appeal of a Java program.  Java provides support for two common image formats: GIF and JPEG.  An image that is in one of these formats can be loaded by using either a URL, or a filename.
 

How to get the object of the image

  
The java.applet.Applet class provides a method getImage() that returns the image object.
 
Syntax
 
The syntax of the getImage funtion to draw the specified image, is:
  1. public Image getImage(URL url. String image)  
  2. {   }  
Some other required methods are:
 
1. public URL getCodeBased() returns the base URL.
 
2. public URL getDocumentBase() returns the URL of the document in which the Applet is embedded. 
 
Example
 
We must insert this image:
 
1.jpg
 
In this example, we show how to insert the image in an Applet.  We use the drawImage() method to display the image.
  1. import java.applet.*;  
  2. import java.awt.*;  
  3. public class ImageGrpcsEx extends Applet  
  4. {  
  5.     Image pic;  
  6.     public void init()  
  7.     {  
  8.         pic = getImage(getDocumentBase(), "images.jpeg");  
  9.     }  
  10.     public void paint(Graphics grp)  
  11.     {  
  12.         grp.drawImage(pic, 10030this);  
  13.     }  
  14. }  
  15. /* 
  16. <applet code="ImageGrpcsEx.class" width="400" height="400"> 
  17. </applet>
  18. */  
Output
 
fig-1.jpg
 

Animation in Applet

 
Applets are widely used in animation and games, for this we need images that must be moved.
 
Example of animation
  1. import java.awt.*;  
  2. import java.applet.*;  
  3. public class AnimationEx extends Applet  
  4. {  
  5.     Image pic;  
  6.     public void init()  
  7.     {  
  8.         pic = getImage(getDocumentBase(), "images.jpeg");  
  9.     }  
  10.     public void paint(Graphics grp)  
  11.     {  
  12.         for (int i = 50; i < 600; i++)  
  13.         {  
  14.             grp.drawImage(pic, i, 30this);  
  15.             try  
  16.             {  
  17.                 Thread.sleep(400);  
  18.             } catch (Exception e) {}  
  19.         }  
  20.     }  
  21. }  
  22. /* 
  23. <applet code="AnimationEx.class" width="400" height="400"> 
  24. </applet> 
  25. */  
Output