Program to create an applet to display "Hello World".

Applets are small java programs that are run on a web page or java compatible web browser.

Java application programs that run on command prompt using java interpreter are called as Java console-based applications. Whereas the java applets can be transported over internet from one computer to another and run using appletviewer or any web browser that supports java. They are included in an HTML page which tells the browser which applets to load.

An applet can perform arithmetic operations, display graphics, play sounds, accept user input, create animation and play interactive games.

Every applet is created by creating sub class of Applet class. An applet is simply a Java class that extends the java.applet.Applet class. There are following steps to create an applet program by first mechanism:
  1. First of all add the following import statements:
    import  java.applet.Applet;
    import  java.awt.Graphics;
  2. Define an applet subclass. Every applet must define a subclass of the Applet class. The Applet class have life cycle methods: init( ), start( ), stop( ), destroy( ), paint( ).
    public  class  HelloWorld  extends  Applet
  3. Every Applet must implement one of the following methods : init( ), start( ) or paint( ). The paint( ) method requires Graphics object as an argument, defined as follows. The Graphics class is present in java.awt package.
    public  void  paint (Graphics g) { ... }
  4. Now use the Graphics class methods like drawString( ), drawLine( ) to draw on Applet window. The complete program is shown in SOURCE CODE section.
  5. Compile the above program using java compiler. Remember that you have to define the subclass with public access specifier.
    After that it will create a .class file by name "HelloWorld.class".
  6. Next create a HTML file and put the <APPLET> tag in it by specifying the class file name in CODE attribute as shown below.
  7. <APPLET  CODE="HelloWorld.class"  WIDTH="100"  HEIGHT="100">
  8. Save the HTML file as "HelloWorldApplet.html" and use appletviewer command to load the applet viewer window.
    appletviewer  HelloWorldApplet.html
In this program, we have created two seperate file, in first file we have created applet class and in second file we have embed the <APPLET> tag in it by specifying class name. In next program we will put the applet tag in same .java file. The output of this program is, it will just display "Hello World !" on applet window. The drawString(String msg, int x, int y) is a method of Graphics class which draws the string in an applet.

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {

public void paint(Graphics g) {
  g.drawString("Hello World !", 10, 30);

<title>Hello World Applet</title>

 <applet code="HelloWorld.class" width="200" height="200">


Commands to Compile & Run Applet programs

C:\>appletviewer HelloWorldApplet.html


1 comment: