Create Software Components 

Using Java Level 2

 

 

Course Info

Scheme

Resources

Tutorials

Java Demos

Utilities

Links


 

   Lecture 3

The Applet Class & Lifecycle 

 

First we will look at the Applet class.  Then this tutorial will walk you through the life cycle of an applet. At the end of the tutorial, you will have created a simple applet that illustrates the four main methods of an applet and the lifecycle of an applet. 

The Applet Class & Methods

The Applet Lifecycle

Finishing Off

Summary


The Applet Class & Methods 

All object-oriented language use classes, objects, (instance of classes) and methods.  When we create our own applet classes, they descend from the Applet class and inherit methods and variables defined in the Applet class.  

Not only do our own applets inherit from the Applet class but also from the superclasses of Applet such as Panel, Container, Component and Object.  

The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly).  Object provides behaviors that are required of all objects running in the Java Virtual Machine. For example, all classes inherit Object's toString method, which returns a string representation of the object.

We are not required to use every inherited method or variable and we are also allowed to re-define an inherited method by overriding that method.  

The diagram below shows the class hierarchy, highlighting the superclasses of Applet .

 

 

The Applet class extends the AWT Panel class, which extends the AWT Container class, which extends the AWT Component class.

  • From Component, an applet inherits the ability to draw components and handle events.

  • From Container, an applet inherits the ability to include other components and to have a layout manager to control the size and position of those components.

  • From Applet, an applet inherits several capabilities, such as loading and unloading.

Although the Applet class inherits many features from ancestral classes such as Panel, Container, Component and Object there are four main methods of the Applet class.  These are:

  • init ()        

An applet can initialize itself. 

 

  • start ()      

An applet  can start running.

  • paint ()      

Graphics shapes such as text, circles rectangles etc. may be drawn onto the applet.

  • stop ()       

An applet  can stop running.

  • destroy ()  

An applet can perform a final cleanup, in preparation for being unloaded and destroyed.

All of these methods are automatically called by a browser when an applet is part of a web page.  These inherited methods are empty, so they don't do any thing until we override them.

 

Override

This means to replace an inherited method with your own version of the method.  Your method will be executed instead of the inherited method.  

For example, when a browser calls an applet's init() method, it first check's to see if an init() method has been defined within the applet itself.  If it hasn't been defined, it looks in the parent classes until it finds an init() method and executes that. 

 

init ()

This method is called by the browser as soon as the applet is loaded.  The implementation of this method provided by the Applet class does nothing.

You should override this method when wishing to set up items for the first time. You should be aware that some browsers always call this method when re-displaying an applet page.

start ()

This method is called by the browser after the init method and starts applet execution.  Some browsers will call this method each time a web page containing the applet is re-visited, skipping the init method.  Some browsers call both the init method and the start method when re-visiting the applet web page.  The implementation of this method provided by the Applet class does nothing.

You should override this method when actions need to be carried out every time the web page is visited or re-visited.  Every applet that does something after initialization must override the start() method.  The start() method usually performs the applet's work.

stop ()

This method is called by the browser when when leaving the applet page and moving to another web page or when quitting the browser.  The implementation of this method provided by the Applet class does nothing.

You should override this method to suspend applet execution and stop the applet from using up system resources when the applet web is no longer being viewed.  As an example, an applet that displays animation should stop trying to draw the animation when the user isn't looking at it.  Most applets that override start() should also override the stop() method. 

destroy ()

This method is called by the browser just before the applet is removed from memory. The implementation of this method provided by the Applet class does nothing. 

You don't usually need to override this method since the stop() method, which is called before destroy(), does everything necessary to shut down the applet's execution. However, destroy() is available for applets that need to release additional resources.

paint ()

This method is called after the init() and start() methods  have completed their execution. It paints - draws - on the  the applet. It is also called automatically each time the  applet needs to be repainted.  Drawing is carried out using a Graphics object g which is automatically  passed to the paint() method.

repaint ()

This method invokes another method called update() which erases any drawing that was done previously on the applet and then invokes the paint() method.

No main() method

An applet runs automatically when its web page is loaded.  There is no main() method in an applet.  In contrast, all Java applications must have a main method. 

 

Not every applet needs to override every one of these methods.  Some very simple applets override only the paint, init or start method.  For example, the "Hello World" applet just displays a string once, using its paint method. 

 

The Applet Lifecycle

Let's write some code that uses all four applet methods and have a look at the lifecycle of the applet.

  1. Create the LifeCycle Source Code

Type the following code in your text editor and save the file as LifeCycle.java.  

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

public class LifeCycle extends Applet {

  public void init() {

    System.out.println("init run");
  }
  public void start() {

    System.out.println("start method");
  }
  public void stop() {

    System.out.println("stop method");
  }

  public void destroy() {

    System.out.println("destroy method");
  }
  public void paint(Graphics g) {
    //Draw a Rectangle around the applet's display area.
    g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
    g.drawString("If you are running this applet from

        appletviewer...", 5, 15);
    g.drawString("...check the Command Prompt for the output", 20, 30);
    g.drawString("If you are running this applet from a 

        HTML page...", 5, 55);
    g.drawString("...check the Java Concole for the output", 20, 70);
    System.out.println("painting");
  }
}

 

  1. Compile Your Code

At the command prompt, compile your source code into bytecode...

 > javac LifeCycle.java 

Check that a class file has been created...

 > dir LifeCycle.*

 

  1. Create a HTMl File

Type the following in your text editor and save the file as LifeCycle.html 

<HTML>
  <HEAD>
    <Title> Life cycle of an Applet </Title>
  </HEAD>
  <BODY>
    <h1> A Look at an Applet Lifecycle </h1>
    <Applet code="LifeCycle.class" width=200 height=100 > 
    </Applet>
  </BODY>
</HTML>

 

  1. Execute your Applet

Let's use appletviewer to execute our code first.  At the command prompt, type...

 > appletviewer LifeCycle.html 

Keep an eye on the command prompt windows, because that is where the output is being sent to.

  • When first starting the applet you should see...

The init and start methods have been executed.

 

  • If you Reload or Restart the applet using the Applet menu, you should see

The stop and destroy methods have been executed, then the applet was reloaded and the init and start methods should execute again.

 

  • If you Close or Quit the applet using the Applet menu, you should see

The stop and destroy methods have been executed.

 

Finishing Off

    Execute your Applet in the Browser

Now use a browser to run your applet.  In this case the output from lines such as System.out.println will be sent to the Java Console.

You should see the Java Console in the Windows Tray

Open up the Java Console by right-clicking on the Java Console icon and selecting Show Console.  Now check out which methods are executed when loading your applet page, moving to a different page then back to your applet page and when quitting the browser.

Summary

To write an applet, you must create a subclass of the java.applet.Applet class.  In your Applet subclass, you must implement at least one of the following methods: init, start, and paint.  The init and start methods, along with stop and destroy, are called at various times in the applet's life cycle. The paint method is called when the applet needs to draw itself to the screen.

Unlike a Java application a Java applet does NOT need to implement a method called main().

You include applets in HTML pages using the <APPLET> tag, e.g.

<Applet code="LifeCycle.class" width=200 height=100 > </Applet>

When a browser user visits a page that contains an applet tag, here is what happens:

  • The browser finds the class file for the applet's Applet subclass. The location of the class file (containing Java bytecodes) is specified with the CODE attribute of the <APPLET> tag.

  • The browser brings the bytecodes over the network to the user's computer.

  • The browser creates an instance of the Applet subclass. 

  • The browser calls the applet's init method. 

  • The browser calls the applet's start method.

Java bytecode is executable code.  You should be aware that loading any executable code over the network is a security risk.  For Java applets, some of this risk is reduced because of various restrictions imposed by the browser on what applets are allowed to do.  These restrictions include disallowing applets from loading code written in any non-Java language, and disallowing applets from reading or writing files on the browser's host computer.   Read more about security restrictions here.

 


That is folks!!

Now try the Applet Sound & Image exercise

 

 

  Site Home 

Java Home   

  Forum  

Course Info

Welcome

Overview

Assessment

Qualification

Scheme of Work

Assignments

Resources

Information

Blackboard

Learning Center

Web Materials

Reading

Java Demos

Utilities

Links

Lecture Materials

Tutorials & Notes

Exercises

Activities

Quizzes

 

Site Home

Top

Unit Home

ADR 2002