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:
- public Image getImage(URL url. String image)
- { }
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:
In this example, we show how to insert the image in an Applet. We use the drawImage() method to display the image.
- import java.applet.*;
- import java.awt.*;
- public class ImageGrpcsEx extends Applet
- {
- Image pic;
- public void init()
- {
- pic = getImage(getDocumentBase(), "images.jpeg");
- }
- public void paint(Graphics grp)
- {
- grp.drawImage(pic, 100, 30, this);
- }
- }
-
-
-
Output
Animation in Applet
Applets are widely used in animation and games, for this we need images that must be moved.
Example of animation
- import java.awt.*;
- import java.applet.*;
- public class AnimationEx extends Applet
- {
- Image pic;
- public void init()
- {
- pic = getImage(getDocumentBase(), "images.jpeg");
- }
- public void paint(Graphics grp)
- {
- for (int i = 50; i < 600; i++)
- {
- grp.drawImage(pic, i, 30, this);
- try
- {
- Thread.sleep(400);
- } catch (Exception e) {}
- }
- }
- }
-
-
-
-
Output