Displaying Images in Java Applets: A Comprehensive Guide
Table of Content:
Applet is mostly used in games and animation. For this purpose image is required to be displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax:
Below method is used draw the specified image.
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer){ ............... ............... }
How to get the object of Image:
The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:
public Image getImage(URL u, String image){ ............... ............... }
Another required methods of Applet class to display image
- public URL getDocumentBase(): is used to return the URL of the document in which applet is embedded.
- public URL getCodeBase(): is used to return the base URL.
Program to display image in applet
We want to print this below image using the applet
Example of Graphics in applet
Program:
File Name : DisplayImageInApplet.java
import java.awt.*; import java.applet.*; public class DisplayImageInApplet extends Applet { Image picture; public void init() { picture = getImage(getDocumentBase(),"atnyla.jpg"); } public void paint(Graphics g) { g.drawImage(picture, 30,30, this); } }
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of drawImage() method of is ImageObserver object. The Component class implements ImageObserver interface. So the current class object would also be treated as ImageObserver because Applet class indirectly extends the Component class.
HTML File::
File Name : MyAppletExample.html
Now Compile the program and run using appletviewer by cmd
Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Users\Hello World>I: I:\>cd Java Programming I:\Java Programming>javac DisplayImageInApplet.java I:\Java Programming>appletviewer MyAppletExample.html