INTRODUCTION TO APPLETS

CONTENTS

1. Introduction
2. The Java applet package
3. Simple example
4. Applet parameters
5. GUI features and embedded URLs
6. Summarys


1. INTRODUCTION

An alternmativec way of running a Java program is from in side a WWW page, a Java program desifned to operate in this manner is termed an applet. On this page we give a simple example of how to create an applet; it is assumed that the reader is familiar with HTML.



2. THE JAVA APPLET PACKAGE

The java.applet package contains several classes including the Applet class which contains the most commonly required methods to create and manipulate applets. The Applet class is a subclass of the Panel, Container and Component classes founf in the awt package.




3. SIMPLE EXAMPLE

To create an applet you must create a subclass of the Applet class including:

  1. init() Called by the browser or applet viewer to inform the applet that it has been loaded into the system.

It is necessary to overide this method with one contained in the programmer's applet. It is also necessary to overide the paint method found in the Component supper class of the Applet class. Some example code is given in Table 1 which produces a classic "hello world" applet. Note that applet classes must always be public and be sub-classes of the class Applet.

// Applet Example
// Frans Coenen
// University of Liverpool, Dept of Comp. Sci.
// Friday 12 January 2000

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

public class AppletEx extends Applet {
    // Override init()
    
    public void init() {
        setBackground(Color.yellow);
	}
	
    // Overidepaint()
    
    public void paint(Graphics g) {
        Font font = new Font("Serif",Font.BOLD,72);
	g.setFont(font);
	g.setColor(Color.blue);
	g.drawString("Hello World",250,150);
	}
    }

Table 1: Classic "hello world" applet

For this to work we need to also write an appropriate HTML file with the name of the applet abd the required width anf height for the applet. Some appropriate HTML code is presented in Table 2 --- I have assumed that this is contained ion the file helloWorld.html.

< HTML>
< HEAD>
< TITLE> Applet Example 1 </TITLE>
</HEAD>
< BODY>
< CENTER>
< APPLET code=AppletEx.class width=900 height=300></APPLET>
</CENTER>
</BODY>
</HTML>

Table 2: "hello world" HTML file

Viewing this using a WWW browser you get a WWW page of the form shown in Figure 1.

HELLO WORLD WWWW PAGE

Figure 1: WWW page produced when viewing the HTML code presented in Table 2 through a WWW browser.

Alternatively you can use the appletviewer program by typing:

appletviewer helloWorld.html

or click here to view to hello world HTML page.




4. Applet Parameters

We can pass arguments to a Java applet in the same way that we can pass command line arguments to Java application programs. In the previous example we "hard coded" the: back and forground colours; the font, font size and look (bold, italic etc.); and the positiojn of the "Hello World" string. These arguments could be passed in as parameterts to the applet. To do this we would have to revise the HTML code as shown in Table 3.


< HTML>
< HEAD>
< TITLE>APPLET EXAMPLE 2< /TITLE>
< /HEAD>
< BODY>
< H1>APPLET EXAMPLE WITH PARAMETER PASSING< /H1>

< P>Example 1< /P>
< CENTER>
< APPLET code=AppletEx2.class width=700 height=300>
	< PARAM NAME=size VALUE="50">
	< PARAM NAME=font VALUE="Serif">
	< PARAM NAME=colour VALUE="red">
	< PARAM NAME=background VALUE="green">
	< PARAM NAME=message VALUE="Frans Coenen in Serif">
< /APPLET>
< /BODY>
< /HTML>
< /CENTER>

< P>Example 2< /P>
< CENTER>
< APPLET code=AppletEx2.class width=700 height=300>
	< PARAM NAME=size VALUE="50">
	< PARAM NAME=font VALUE="SansSerif">
	< PARAM NAME=colour VALUE="orange">
	< PARAM NAME=background VALUE="blue">
	< PARAM NAME=message VALUE="Frans Coenen in SansSerif">
< /APPLET>
< /CENTER>

< P>Example 3< /P>
< CENTER>
< APPLET code=AppletEx2.class width=700 height=300>
	< PARAM NAME=size VALUE="50">
	< PARAM NAME=font VALUE="Monospaced">
	< PARAM NAME=colour VALUE="yellow">
	< PARAM NAME=background VALUE="cyan">
	< PARAM NAME=message VALUE="Frans Coenen in Monospaced">
< /APPLET>
< /CENTER>

< P>Example 4< /P>
< CENTER>
< APPLET code=AppletEx2.class width=700 height=300>
	< PARAM NAME=size VALUE="50">
	< PARAM NAME=font VALUE="Dialog">
	< PARAM NAME=colour VALUE="green">
	< PARAM NAME=background VALUE="magenta">
	< PARAM NAME=message VALUE="Frans Coenen in Dialog">
< /APPLET>
< /CENTER>

< P>Example 5< /P>
< CENTER>
< APPLET code=AppletEx2.class width=700 height=300>
	< PARAM NAME=size VALUE="50">
	< PARAM NAME=font VALUE="DialogInput">
	< PARAM NAME=colour VALUE="blue">
	< PARAM NAME=background VALUE="black">
	< PARAM NAME=message VALUE="Frans Coenen in DialogInput">
< /APPLET>
< /CENTER>
< /BODY>
< /HTML>

Table 3: HTML code from Table 2 revised to include parameter passing.

Note, from Table 3, that each parameter is given a name and a sting value. The parameters are then obtained using the getParameter method from the Applet class which has the general form:

getParameter( < PARAMETER NAME > );

The getParameter method returns the value of the named parameter as a string; thus, in some cases, it will be necessary to convert this to a numeric equivalent. An illustration is given in Table 4 which should be used in conjunction with the example HTML code presented in Tabled 3. In Table 4 remember that the setBackground method is contained within the Component class of which the Applet class is a sub class. However, the setColor method is a Graphics class method.

Note: The parameter passing example presented here is founded on a similar exampled presented in Holmes (1998).

// Applet Example
// Frans Coenen
// University of Liverpool, Dept of Comp. Sci.
// Friday 12 January 2000

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

public class AppletEx2 extends Applet {
    int sizeParameter;
    String fontParameter;
    String colourParameter;
    String backgroundParameter;
    String messageParameter;

    /* Convert Colour String: Convert string value to colour object,
    if string value does not exist select blaclk  by default. */
    
    private Color convertColourString(String colour) {
        if      (colour.equals("red"))     return(Color.red);
        else if (colour.equals("orange"))  return(Color.orange);
        else if (colour.equals("yellow"))  return(Color.yellow);
        else if (colour.equals("green"))   return(Color.green);
        else if (colour.equals("blue"))    return(Color.blue);
        else if (colour.equals("cyan"))    return(Color.cyan);
        else if (colour.equals("magenta")) return(Color.magenta);
        else                               return(Color.black);
        }

    /* Override init() */
    
    public void init() {
        sizeParameter       = new Integer(getParameter("size")).intValue();
        fontParameter       = getParameter("font");
	colourParameter     = getParameter("colour");
	backgroundParameter = getParameter("background");
	messageParameter    = getParameter("message");
	}
	
    /* Override paint() */
    
    public void paint(Graphics g) {        
        // Define font

        Font font = new Font(fontParameter,Font.BOLD,sizeParameter);
	g.setFont(font);

        // Define font colours. 

        setBackground(convertColourString(backgroundParameter));
	g.setColor(convertColourString(colourParameter));

        // Output message

	g.drawString(messageParameter,25,150);
	}
    }

Table 4: Java code from Table 3 revised to include parameter passing.

To see the effect of the above example click here.




5. Applets as GUIs with embedded URLS

All the GUI features described in earlier examples can be embedded in applets. For example we can include buttons as shown in the Java code presented Table 5. Note that, as with buttons placed in GUIs we need to include an actionPerformed method to be activated in the event of a button click.

In the example code presented in Table 5 a button press causes the applet to display a particular WWW page. To process URLs incoporated into an applet the URL class contained on the net package provides many useful methods. The class URL includes a number of constructors one of which is of the form:

public URL(String spec)

where the argument, spec must be a "well formed" absolute URL (not a relative URL). If it is not a well formed URL a MalformedURLException is thrown. To show a WWW page, from an Applet, we need to use the showDocument method from the abstract interface AppletContext. This interface allows an applet to interact with the "context" of (say) the WWW browser in which it is running. To inoke the showDocument method we require an AppleCopntext object. We can get such an object using the getAppletContext() method found in the Applet class.

// Applet Example
// Frans Coenen
// University of Liverpool, Dept of Comp. Sci.
// Friday 12 January 2000

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

public class AppletEx3 extends Applet implements ActionListener {
    
    // Array with font alternatives

    String[] names = {"Introduction","The Java applet package",
    	"Simple example","Applet parameters","GUI Features"};
    String[] urls = {
        "http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#introduction",
        "http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#package",
        "http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#example",
	"http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#parameters",
	"http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#guiFeatures"};
    Button[] button = new Button[names.length];
    
    /* Override init() */
    
    public void init() {
        setLayout(null);
	setBackground(Color.black);
	Font font = new Font("Serif",Font.BOLD,25);
        // Buttons
        
        for (int index=0; index < names.length;index++) {
            button[index] = new Button(names[index]);
	    button[index].setFont(font);
            button[index].setLocation(10,10+(50*index));
            button[index].setSize(300,30);
            button[index].setBackground(Color.yellow);
            button[index].addActionListener(this);
            add(button[index]);
            }
        }

    /* Action Listener */

    public void actionPerformed(ActionEvent event) {
        // Get name of pressed button

        Object source = event.getActionCommand();
        
        // Get url and try to connect
 
        for (int index=0;index < names.length;index++) {
            if (source.equals(names[index])) {
                try {
                    URL site = new URL(urls[index]);
                    getAppletContext().showDocument(site);
                    }
                catch (MalformedURLException m) {
                    System.exit(1);
                    }
                return;
                }
            }
        }         
    }

Table 5: Java code demonstrating the inclusasion of GUI features in an Applet and the invocation of a URL from an Applet.

The HTML code required to invoke the applet given in Table 5 is presrented in Table 6. To view the effect of running this code click here.


< HTML>
< HEAD>
< TITLE>APPLET EXAMPLE 3< /TITLE>
< /HEAD>
< BODY>
< H1>APPLET EXAMPLE 3.1< /H1>
< CENTER>
< APPLET code=AppletEx3.class width=320 height=240>
< /APPLET>
< /CENTER>
< /BODY>
< /HTML>

Table 6: HTML code to invoke Applet presented in Table 5.




6. Summary

On this page we have introduced to concept of an Applet and illustred:

  1. Argument passing to Applets,
  2. Inclusasion of GUI features in Applets, and <
  3. Invocation of URLs from Applets.

In Table 7 these features are all combined into a single applet program. The associated HTML code is presented in Table 8.

// Applet Example
// Frans Coenen
// University of Liverpool, Dept of Comp. Sci.
// Friday 12 January 2000

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

public class AppletEx4 extends Applet implements ActionListener {
    
    // Array with font alternatives

    String[] names = new String[3];
    String[] urls  = new String[3];
    Button[] button = new Button[names.length];
    
    /* Override init() */
    
    public void init() {
        // Get pameters
	
        names[0] = getParameter("name1");
	names[1] = getParameter("name2");
	names[2] = getParameter("name3");
	urls[0]  = getParameter("url1");
	urls[1]  = getParameter("url2");
	urls[2]  = getParameter("url3");
        
	// Layout
	setLayout(null);
	setBackground(Color.black);
	Font font = new Font("Serif",Font.BOLD,20);
        
	// Buttons
        
	int width = 210;
        for (int index=0; index < names.length;index++) {
            button[index] = new Button(names[index]);
	    button[index].setFont(font);
            button[index].setLocation(10+((width+10)*index),50);
            button[index].setSize(width,50);
            button[index].setBackground(Color.yellow);
            button[index].addActionListener(this);
            add(button[index]);
            }
        }

    /* Action Listener */

    public void actionPerformed(ActionEvent event) {
        // Get name of pressed button

        Object source = event.getActionCommand();
        
        // Get url and try to connect
 
        for (int index=0;index < names.length;index++) {
            if (source.equals(names[index])) {
                try {
                    URL site = new URL(urls[index]);
                    getAppletContext().showDocument(site);
                    }
                catch (MalformedURLException m) {
                    System.exit(1);
                    }
                return;
                }
            }
        }         
    }

Table 7: Summary.

< HTML >
< HEAD >
< TITLE >APPLET EXAMPLE 4< /TITLE >
< /HEAD >
< BODY >
< H1 >APPLET EXAMPLE SUMMARY< /H1 >

< CENTER >
< APPLET code=AppletEx4.class width=700 height=150 >
	< PARAM NAME=name1 VALUE="Introduction" >
	< PARAM NAME=name2 VALUE="The Java applet package" >
	< PARAM NAME=name3 VALUE="Simple example" >
	< PARAM NAME=url1  VALUE="http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#introduction" >
	< PARAM NAME=url2  VALUE="http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#package" >
	< PARAM NAME=url3  VALUE="http://www.csc.liv.ac.uk/~frans/COMP101/AdditionalStuff/Applets/applets.html#example" >
< /APPLET >
< /BODY >
< /HTML >

Table 8: HTML code to invoke Applet presented in Table 7.

To view the effect of running the above code click here.




Created and maintained by Frans Coenen. Last updated 31 January 2001