Tuesday, 29 November 2016

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:
  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 HelloWorldApplet 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.
    javac  HelloWorldApplet.java
    After that it will create a .class file by name "HelloWorld.class".
  6. 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.
  7. /* <applet  code="HelloWorldApplet.class"  width="100"  height="100">
     </applet>
    */
  8. Use appletviewer command to load the applet viewer window.
    appletviewer HelloWorldApplet.java
The output is shown in OUTPUT section.


PROGRAM
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


No comments:

Post a Comment