Monday, 12 September 2011

Applet Hello World

This example introduces you with the Applet in Java. You will learn how to develop applet code and run in the browser.
Applet is a program provided by java which is designed for execution within the web browser. Applets are mostly used for a small internet and intranet applications because of small size and it's compatibility among almost all web browsers. Applets are also very secure.  For example, Applets can be used to serve animated graphics on the web.
This example creates a simple applet that displays Hello World message.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class HelloWorldApplet extends Applet{
  public static void main(String[] args){
  Frame frame = new Frame("Roseindia.net");
  frame.setSize(400,200);
  Applet app = new HelloWorldApplet();
  frame.add(app);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  System.exit(0);
  }
  });
  }
  public void paint(Graphics g){
  g.drawString("Hello World!",200,100);
  }
}
Compiling Applets:
javac HelloWorldApplet.java
Running Applet from console:
java HelloWorldApplet
Running Applet from Web browser:
Running applet in browser is very easy job, create an html file with the following code:
<html>
<head>
<title>A Simple Applet program</title>
</head>
<body>
<APPLET CODE="HelloWorldApplet.class" WIDTH=700 HEIGHT=500>
</APPLET>
</body>
</html> 
The Applet tag in html is used to embed an applet in the web page.

<APPLET CODE="HelloWorldApplet.class" WIDTH=700 HEIGHT=500>

CODE tag is used to specify the name of Java applet class name. To test your applet open the html file in web browser. You browser should display applet. You can also try this applet online by clicking on the following link.
Try the example online
Download Applet Example
Post a Comment