Applets are written in Java and they are viewed using Applet Viewer or a Java enabled browser. Applets are included in HTML page using <APPLET> tag, and then these can be viewed by the users having Java enabled browser. Thing to note is that Applets are not executed on the server side. They are transferred to userís machine and then executed by the browser's Java Virtual Machine (JVM).

The <APPLET> tag

Applet tag is used to add the applet into HTML page.
Java Code:
<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
</APPLET>
One has to specify the applet class name, along with the width and height of the applet. This is a way to inform the browserís JVM how to handle the applet.

Applets with parameters

Applets also accept parameters. These parameters can be used for customization.

Java Code:
<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
<PARAM NAME=parameter1Name VALUE=aValue>
<PARAM NAME=parameter2Name VALUE=anotherValue>
</APPLET>
Time for an example:

Java Code:
:
<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160
 ALT="If you could run this applet, you'd see some animation">
<PARAM NAME="imageSource" VALUE="images/Beans">
<PARAM NAME="backgroundColor" VALUE="0xc0c0c0">
<PARAM NAME="endImage" VALUE=10>
<PARAM NAME="soundSource" VALUE="audio">
<PARAM NAME="soundtrack" VALUE="spacemusic.au">
<PARAM NAME="sounds"
       VALUE="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8au|9.au|0.au">
<PARAM NAME="pause" VALUE=200>
Your browser is completely ignoring the APPLET tag!
</APPLET>
In applet, you may get the parameters and use them accordingly.
Java Code:
int requestedWidth = 0;
. . .
String windowWidthString = getParameter("WINDOWWIDTH");
if (windowWidthString != null) {
    try {
        requestedWidth = Integer.parseInt(windowWidthString);
    } catch (NumberFormatException e) {
        //Use default width.
    }
}
Some browsers do not have JVM so they cannot display the applets. In such case, plan text (without any tag) written inside applet tag will be displayed. In the example above, following message will be displayed if the browser does not support applet.
Java Code:
Your browser is completely ignoring the APPLET tag!
The CODEBASE attribute

The CODEBASE attribute in the APPLET tag specifies the directory where the applet class exist. This is ignored in case the applet class exists in the same directory as the HTML file containing the applet.
Java Code:
<APPLET CODE=MyApplet.class CODEBASE="applets/"
        WIDTH=500 HEIGHT=20>
</APPLET>
HelloWorld Applet

A simple example of Applet is shown below.
Java Code:
public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
	g.drawRect(0, 0, 
		   getSize().width - 1,
		   getSize().height - 1);
        g.drawString("Hello world!", 5, 10);
    }
}
Applet is simply a class that inherits from java.applet.Applet or javax.applet.JApplet. If you are not using Swing components, then no need to use JApplet.

Lifecycle of an Applet

All applets have the following four methods:
Java Code:
public void init();
public void start();
public void stop();
public void destroy();
Let me write few lines about each method.

init method is used to initialize the applet each time it's loaded (or reloaded).
start method to start the applet's execution, such as when the applet is loaded or when the user revisits a page that contains the applet.
stop to stop the applet's execution, such as when the user leaves the applet's page or quits the browser.
destroy method is used to perform a final cleanup in preparation for unloading.

Applets inherit these methods from their super class java.applet.Applet. There are other inherited methods too but the main ones are listed. Remember, JApplet also inherits from Applet.

Time for an example:
Java Code:
import java.applet.Applet;
import java.awt.Graphics;


public class HelloWorld extends Applet {

	StringBuffer buffer;

	public void init() {
		buffer = new StringBuffer();
		addItem("initializing... ");
	}

	public void start() {
		addItem("starting... ");
	}

	public void stop() {
		addItem("stopping... ");
	}

	public void destroy() {
		addItem("preparing for unloading...");
	}

	private void addItem(String newWord) {
		System.out.println(newWord);
		buffer.append(newWord);
		repaint();
	}

	public void paint(Graphics g) {
		g.drawRect(0, 0, 
				getWidth() - 1,
				getHeight() - 1);
		g.drawString(buffer.toString(), 5, 15);
	}
}
Run this applet from your IDE (Eclipse) and see the messages on the console.

An applet can react to major events in the following ways:

It can initialize itself.
It can start running.
It can stop running.
It can perform a final cleanup, in preparation for being unloaded.

The Paint method

Applets inherit the paint method from the Abstract Window Toolkit (AWT) Container class. Paint method is used to draw objects on the screen. Lets go through an example:

Java Code:
public void paint(Graphics g) {
	//Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0, 
		   getWidth() - 1,
		   getHeight() - 1);

	//Draw the current string inside the rectangle.
        g.drawString(buffer.toString(), 5, 15);
    }
Event handling

Applets inherit a group of event-handling methods from the Container class.
The Container class defines several methods (processKeyEvent, processMouseEvent etc) for handling particular types of events. Applet inherits these events from the Container class. In order to react to an event, an applet must override the appropriate event-specific method. Review the example below. The applet class implements MouseListener interface. It has following four methods that have to be implemented.

Java Code:
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
If you are not planning to have the functionality of some event, then simply implement the event and leave its body blank.

Time for an example:

Java Code:
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet 
			 implements MouseListener {

    StringBuffer buffer;

    public void init() {
	addMouseListener(this);
	buffer = new StringBuffer();
        addItem("initializing... ");
    }

    public void start() {
        addItem("starting... ");
    }

    public void stop() {
        addItem("stopping... ");
    }

    public void destroy() {
        addItem("preparing for unloading...");
    }

    void addItem(String newWord) {
        System.out.println(newWord);
        buffer.append(newWord);
        repaint();
    }

    public void paint(Graphics g) {
        g.drawRect(0, 0, 
		   getWidth() - 1,
		   getHeight() - 1);
        g.drawString(buffer.toString(), 5, 15);
    }

    public void mouseEntered(MouseEvent event) {
    	addItem("mouseEntered!... ");
    }
    public void mouseExited(MouseEvent event) {
    }
    public void mousePressed(MouseEvent event) {
    }
    public void mouseReleased(MouseEvent event) {
    }

    public void mouseClicked(MouseEvent event) {
	addItem("click!... ");
    }
}
Output:
Applet Programming-applet_events1.png

Applet Ė Drawing lines

Presented below is an Applet that draws a pattern of lines.
Java Code:
public class HelloWorld extends Applet {

   int width, height;

   public void init() {
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.black );
   }

   public void paint( Graphics g ) {
      g.setColor( Color.green );
      for ( int i = 0; i < 10; ++i ) {
         g.drawLine( width, height, i * width / 10, 0 );
      }
   }
}
Mouse event example

Following is an interesting example that shows how to use mouse events in an Applet. Just try to run it on you machine and play around for better understanding.
Java Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class HelloWorld extends Applet
   implements MouseListener, MouseMotionListener {

   int width, height;
   int mx, my;  // the mouse coordinates
   boolean isButtonPressed = false;

   public void init() {
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.black );

      mx = width/2;
      my = height/2;

      addMouseListener( this );
      addMouseMotionListener( this );
   }

   public void mouseEntered( MouseEvent e ) {
      // called when the pointer enters the applet's rectangular area
   }
   public void mouseExited( MouseEvent e ) {
      // called when the pointer leaves the applet's rectangular area
   }
   public void mouseClicked( MouseEvent e ) {
      // called after a press and release of a mouse button
      // with no motion in between
      // (If the user presses, drags, and then releases, there will be
      // no click event generated.)
   }
   public void mousePressed( MouseEvent e ) {  
// called after a button is pressed down
      isButtonPressed = true;
      setBackground( Color.gray );
      repaint();
      // "Consume" the event so it won't be processed in the
      // default manner by the source which generated it.
      e.consume();
   }
   public void mouseReleased( MouseEvent e ) {  
// called after a button is released
      isButtonPressed = false;
      setBackground( Color.black );
      repaint();
      e.consume();
   }
   public void mouseMoved( MouseEvent e ) {  
// called during motion when no buttons are down
      mx = e.getX();
      my = e.getY();
      showStatus( "Mouse at (" + mx + "," + my + ")" );
      repaint();
      e.consume();
   }
   public void mouseDragged( MouseEvent e ) {  
// called during motion with buttons down
      mx = e.getX();
      my = e.getY();
      showStatus( "Mouse at (" + mx + "," + my + ")" );
      repaint();
      e.consume();
   }

   public void paint( Graphics g ) {
      if ( isButtonPressed ) {
         g.setColor( Color.black );
      }
      else {
         g.setColor( Color.gray );
      }
      g.fillRect( mx-20, my-20, 40, 40 );
   }
}
getApplets() method

getApplets() finds all the applets represented by this applet context and returns an enumeration. Then we can get each applet and do what ever we like with it.
Java Code:
public void printApplets() {
    //Enumeration will contain all applets on this page (including
    //this one) that we can send messages to.
    Enumeration e = getAppletContext().getApplets();
    . . .
    while (e.hasMoreElements()) {
        Applet applet = (Applet)e.nextElement();
        String info = ((Applet)applet).getAppletInfo();
        if (info != null) {
            textArea.appendText("- " + info + "\n");
        } else {
            textArea.appendText("- "
                                + applet.getClass().getName()
                                + "\n");
        } 
    }
    . . . 
}
Reading system properties from an Applet

Sometimes you need to write an applet that can read the system properties from userís system. You may then want to display those details to the user. It is possible with applets but there are some properties that you cannot get from applets.

Following are the properties that you can get from an applet:

"path.separator"
"java.class.version"
"java.vendor"
"java.vendor.url"
"java.version"
"line.separator"
"os.arch"
"os.name"
"path.separator"


You may not access following properties:

"user.name"
"user.home"
"user.dir"
"java.home"
"java.class.path"
Reading a property from an applet, we use System class as shown below:
Code:
String newline = System.getProperty("line.separator");
The screen shot of an applet that read system properties from my machine is shown below:

Applet Programming-applet_properties.png

Security Restrictions

When you are using applets, you should be careful about he security restrictions. You donít want the users or your audience to complain that your applet is not doing what it should be doing.

Just remember that each browser (Internet explorer, Mozilla FireFox, Netscape Navigator etc) has a SecurityManager object that implements its security policies. When a SecurityManager detects a violation, it throws a SecurityException. Your applet can catch this SecurityException and react appropriately. Follows are the restrictions on applets.

- An applet cannot load libraries or define native methods.
- It cannot ordinarily read or write files on the host that's executing it.
- It cannot make network connections except to the host that it came from.
- It cannot start any program on the host that's executing it.
- It cannot read certain system properties.
- Windows that an applet brings up look different than windows that an application brings up.

Applets communication with server

The subject topic is of great interest. Is it really possible for an applet to communicate with the server after all the security limitations? The answer is yes. This is possible but with a limitation. The only host an applet can communicate with is the host it was delivered from.

To get the host from applet, we use the following line of code:
Java Code:
String host = getCodeBase().getHost();
User interface components on Applet

Applets can surely have UI components on it to get input from the user. You may have following components on the applet:

- Buttons (javax.swing.JButton)
- Checkboxes (javax.swing.JCheckBox)
- Single-line text fields (javax.swing.JTextField)
- Larger text display and editing areas (javax.swing.JTextArea)
- Labels (javax.swing.JLabel)
- Lists (javax.swing.JList)
- Pop-ups (javax.swing.Popup)
- Scrollbars (javax.swing.JScrollBar)
- Sliders (javax.swing.JSlider)
- Drawing areas (java.awt.Canvas)
- Menus (javax.swing.JMenu,javax.swing.JMenuBar javax.swing.JMenuItem, javax.swing.JCheckBoxMenuItem)
- Containers (javax.swing.JPanel, javax.swing.JWindow and its subclasses)

After getting the input from the user, you may send the data to the server (from where the applet was sent). An example would be an applet signup form which takes the data from the user and then sends the data to the servlet which saves the data into a database.
Java Code:
JTextField field;
Ö
   private void createGUI() {        
        //Create the text field and make it uneditable.
        field = new JTextField();
        field.setEditable(false);

        //Set the layout manager so that the text field will be
        //as wide as possible.
        setLayout(new java.awt.GridLayout(1,0));

        //Add the text field to the applet.
        add(field);
    }
Conclusion

Creating user friendly and effective applets is fun. You can do a lot of things in an applet but one should know their limitations before using.