An applet is a class file that is specially written to display graphics in a web browser. Applets are embedded in web pages using the HTML tag <Applet>. Java applets are downloaded automatically and run by the web browser. Any web-browser that supports Java, such as Applet Viewer, can be used to transport applets to the Internet. An applet can perform many functions such as graphics, play sound, animation, arithmetic operations, play games etc.
Applets differ from application programs in the sense that they do not use main() program for initiating the execution of code. They do not run independently but from inside a web page that makes an efficient use of HTML tags. To build an applet code, we need to include certain packages like java.awt and java.applet that contains the Graphics class that provides methods where the output of all applet operations are performed. This applet uses nothing from the AWT besides the Graphics class. A simple program using applet looks like:
This program Java Applet Hello World Examples introduces the Applet in Java. You will learn in this example how to develop and run applet code in browser.This program Java Applet Hello World Examples creates a simple applet that displays Hello World message.
import java.applet.Applet; import java.awt.Graphics; public class HelloAppletWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello World!", 200, 100); } }
Compiling Applets:
javac HelloAppletWorld.java
Running this HelloAppletWorld program from Web browser:
Running applet program with web browser is easy job, create an
HelloAppletWorld.html file with the below code:
<html> <head> <title>Java Applet Hello World Examples</title> </head> <body> <applet code="HelloAppletWorld.class" width="500" height="500"></applet> </body> </html> The Applet tag in HelloAppletWorld.html is used to embed an applet in the web page. <applet code="HelloAppletWorld.class" width="500" height="500"></applet>