Program to create "Hello World" applet with applet tag in comments
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. In this program, we embed the APPLET tag in same JAVA source file. There are following steps to create an applet program by second mechanism:
- First of all add the following import statements:
import java.applet.Applet; import java.awt.Graphics;
- 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 HelloWorldApplet extends Applet
- 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) { ... }
- Now use the Graphics class methods like drawString( ), drawLine( ) to draw on Applet window. The complete program is shown in SOURCE CODE section.
- 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".javac HelloWorldApplet.java
- Next put the <APPLET> tag in the same .java file above or below the class definition with CODE in multiline comments attribute as shown below.
- Use appletviewer command to load the applet viewer window.
appletviewer HelloWorldApplet.java
/* <applet code="HelloWorldApplet.class" width="100" height="100">
</applet>
*/
PROGRAM
C:\>javac HelloWorldApplet.java
C:\>appletviewer HelloWorldApplet.java
OUTPUT
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World !", 10, 30);
}
}
/*
<applet code="HelloWorldApplet" height="600" width="600">
</applet>
*/
Commands to Compile and Run Applet program
C:\>javac HelloWorldApplet.java
C:\>appletviewer HelloWorldApplet.java
OUTPUT