CA597 Tutorial - Simple Applets


Applet Structure

Every applet extends the java.applet.Applet class. Applets don't have a main() method. Instead, their structure is as follows:
         import java.applet.Applet;

         public class Simple extends Applet 
	 {
	      ...

              public void init() {
	      // called by the browser when the Web page containing
	      // the applet is loaded
                  ...
              }

              public void start() {
	      // called by the browser after the init() method and 
	      // everytime the Web page is visited
                  ...
              }

              public void stop() {
	      // called by the browser when the Web page containing
	      // the applet becomes inactive
                  ...
              }

              public void destroy() {
	      // called by the browser when the browser exists
                  ...
              }

	      // other methods ...
          }
Browsers call the applet methods. By default, these methods do nothing.

A simple executable example (from Sun's tutorial) which uses basic graphics method to draw a rectangle:

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

         public class Simple extends Applet {

             StringBuffer buffer = new StringBuffer();

             public void init() {
                 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, size().width - 1, size().height - 1);
                 g.drawString(buffer.toString(), 5, 15);
             }
         }

Using GUI Components

An applet is a panel, i.e. the class Applet is a subclass of the AWT class Panel. Panels are invisible GUI components which are used to group components in a window. Java offers several layout managers to layout the components. There is a default one, called FlowLayout, which we use for the moment. Being a panel means that an applet can contain GUI components such as buttons, textfields, labels, checkboxes etc, even panels themselves.

These GUI components can be defined in your applet class

	import java.applet.*;
	import java.awt.*;
	
	public class SimpleApplet extends Applet
	{
        	private TextField message = null ;
        	private Button button = null;
Besides the applet-class, we also need to import the java.awt class in order to get easy access to the GUI features.

In this example we have defined two components:

Now, we are going to create button and textfield objects. We also set a property of the textfield.

	button = new Button("PRESS ME");
        message = new TextField(30);
        message.setEditable(false);
Button(..) and TextField(..) are the constructors of the corresponding classes. The button gets a name, and the textfield will be created as a 30 character long field. We won't allow the Textfield to be edited.

The most sensible place to do these initialisations is the applet's init() method:

public void init()
        {
                button = new Button("PRESS ME");
                message = new TextField(30);
                message.setEditable(false);

The next task is to add the two components to the panel:

	add(button);
        add(message);
This is also done within the init() method. This is all we need to get a - rather inactive - applet.

Event Handling

In order to introduce activity - let the applet react to pressing the button - we need to understand the Java event handling features.

Events are signals created by user actions: pressing a button, moving the mouse, etc. A program can react to an event or ignore it.

GUI components (such as a button) which generate events, are called source objects of an event. In order to be notified about occuring events a program has to register itself with the source object. Such a program is called a listener.

Several event types exist:

If we want our program to react on clicking the button, which is an action event, we need to express that. Our applet has to be defined as an implementation of an (abstract) class ActionListener which listens to action events.

	public class SimpleApplet extends Applet
                          	  implements ActionListener
The registration with the button-object is done in the init() method:
	button.addActionListener(this);
Action events have to be handled by a method called actionPerformed(..). actionPerformed is the event handler for ActionEvents.
        public void actionPerformed(ActionEvent e)
        {
                String actionCommand = e.getActionCommand();
                if (e.getSource() instanceof Button)
                        if (actionCommand.equals("PRESS ME"))
                        {
                                if (pressed)
                                {
                                        pressed = false;
                                        message.setText("");
                                }
                                else
                                {
                                        pressed = true;
                                        message.setText("Thank You");
                                }
                        }
        }
This method stores the name of the action - in our case it should be the name of the button. Then it checks whether the event originates from a button. Remember that there might be various sources of an action event. If the command name is really "PRESS ME", we can react to the button event. Alternatingly, the applet display an empty string or "Thank You" in the textfield.

Here is the complete Java applet source code, implementing a simple interactive applet.

//
//      a Simple Applet
//      based on the CA587 applet
//      updated by Claus Pahl
//      to include listeners
//

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleApplet extends Applet
                          implements ActionListener
{
        private TextField message = null ;
        private Button button = null;
        private boolean pressed = false;

        public SimpleApplet()
        {
        }

        public void init()
        {
                button = new Button("PRESS ME");
                message = new TextField(30);
                message.setEditable(false);

                add(button);
                add(message);

                button.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e)
        {
                String actionCommand = e.getActionCommand();
                if (e.getSource() instanceof Button)
                        if (actionCommand.equals("PRESS ME"))
                        {
                                if (pressed)
                                {
                                        pressed = false;
                                        message.setText("");
                                }
                                else
                                {
                                        pressed = true;
                                        message.setText("Thank You");
                                }
                        }
        }
}

You can see how the applet works here !!!

How to Compile and Start Your Applet

How to Extend Your Applet

Before you start working on the applet, it is important to understand event handling. If you feel you need more background, look at an introduction to event handling; more material is here.

You can extend an applet in the following ways: