Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Steps to Java Internationalization (i18n)

Java Applets in Education

Java #6 I Wanna hold your hand - longer

Mouse Event Handling in Java 1.0

Java #5 I Wanna hold your hand

Java Applets #4

Java Applets #3

Java Applets #1

Java Applets #2

You are here: irt.org | Articles | Java | Java Applets #2 [ previous next ]

Published on: Saturday 21st March 1998 By: Tarique Sani

Introduction

"What a rip off! a Java less Java article" this was the first Email review of my article that I got for my previous article. It somehow makes me feel obliged to defend my self! As I had already mentioned this series is based on my own learning experiences and will tend to follow, more or less, the pattern in which I learnt things. My learning methodology is what my teachers at school called "entirely wrong" and the earst while USSR called "Retro Engineering". In more details - I take an program I like (applets in this instance), learn to use it, then take it apart, and try to figure out what goes where. Do that enough number of times and Voila! You are soon writing your own apps. I have found that this method minimises lag period and enhances productivity. Proof? - I got you up and running with a Java applet in the very first article.

Also let me make it clear that I am not going to explain each and every keyword or syntax of the Java Language here, the best place to look for that is your Java Development Kit (JDK) itself, most distributions come with complete API reference in HTML format, if yours did not, don't depair just run the JAVADOC program which comes with every JDK. And if you don't want to do that either just download the latest documentation from http://java.sun.com/products/jdk/1.1/ if you find this site too busy then download it from my site (653 kb). It is in windows help file format. Anyway it is said that the syntax for Java is very similar to C & C++, hence people who have been programming in C will find it very easy. I can't vouch for that because I don't know anything about C or C++ (Really-Cross my heart).

Skeleton of an Applet

Whew! enough of justifications - now for the real thing. All but most trivial applets comprise of a set of methods that provide the basic mechanism by which the browser interfaces to the applet to control its execution. Four of these methods - init(), start(), stop(), and destroy() - are defined in Applet. Another, paint(), is defined by the AWT (Abstract Windows Toolkit) Component class. Default implementation for all these methods are provided, hence Applets do not need to define those methods that they do not use. The following is a skeleton of an Applet showing all the five methods.

//An Applet Skeleton.
import java.awt.*;
import java.applet.*;

// The default HTML tag goes here
/*
  <applet code="skeleton" width=200 height=200>
  </applet>
*/

public class skeleton extends Applet {
    //Called first
    public void init() {
        //initialization routine go here
    }
    
    //Called second. after init(). Also whenever the applet restarts
    public void start() {
        // Start or Resume execution
    }
    
    //Called when the applet is stopped.
    public void stop() {
        //Suspends execution
    }
    
    //Called when applet is terminated. Last method to be executed.
    public void destroy() {
        //Perform shut down activities
    }
    
    //Called when an applet's window must be restored.
    public void paint (Graphics g) {
        //Redisplay contents of window
    }
}

It is obvious that this skeleton does not do anything (no not even "Hello World") none the less it can be compiled and run.

The observant amongst you must have noticed that there are a few lines of HTML stuck at the begining of the applet source code, this is very convienient for two reasons. One - you need not have a separate HTML file to run your applet using the appletviewer, the appletviewer just uses this piece of HTML if a separate HTML file is not provided! Two - this way your code is documented with a prototype of necessary HTML.

Applet - it's Life & Death

It is important that you understand the order in which the applet calls the methods shown in the above skeleton, otherwise the birth pangs of your applet may never get over! When an applet begins the AWT calls the following methods in this sequence

When an applet dies (or is terminated), the following sequence of method calls takes place:

Lets have a closer look at these methods.

init()

The init() method is the first method to be called. This is where you should initialise variables. This method is called only once during the run time of your applet. Lets see a simple init() method

public void init() {
   setBackground(Color.cyan);
   setForeground(Color.red);
   msg= "Inside init() --"
}

No explainations required, I guess?

start()

The start() method is called after init(). It is also called to restart an applet after it has been stopped. Where as init() is called once - the first time an applet is loaded - start() is called each time an applet's HTML document is displayed on screen. So, if a user leaves a web page and comes back, the applet resumes execution at start().

paint()

The paint() method is called each time your applet's output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window was resized. paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint() is called. The paint() method has one parameter of type Graphics. This is needed for the applet to know where the applet should paint its output.

stop()

The stop() method is called when a web browser leaves the HTML document containing the applet - You should use stop() to suspend threads that don't need to run when it is not visible, like background animations. You can restart them when start() is called if the user returns to the page.

destroy()

The destroy() method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop() method is always called before destroy().

update()

OK! OK! I had not mentioned this one above - but believe me it is important in some situations your applet may need to overide the update() method. This method is defined by the AWT and is called when your applet has requested that a portion of its window be redrawn. The problem is that the default version of update() first fills an applet with the default background colour and then calls paint(), this gives rise to a flash of default color (usually gray) each time update is called. To avoid this you define your update() method such that it performs all necessary display activities [NOTE: if you define your own update() method then the default update() is not called - this is called overriding]. The paint() in this case will simly call update(). Take a look at the following piece of code for better understanding.

public void update(Graphic g) {
     //Redisplay your window here.
}

public void paint(Graphics g) {
     update(g) // call to the update()method.
}

You need to override update() only when needed.

A Simple Applet

Let now write an applet which really does something. Just something, not something useful!

/* This Applet sets the foreground and background colors and out puts a string. */
import java.awt.*;
import java.applet.*;

/* 
   <applet code="Simple" width=300 height=50>
   </applet>
*/
public class Simple extends Applet {
   string msg;
   
   // set the foreground and background colors.
   public void init() {
      setBackground(Color.cyan);
      setForeground(Color.red);
      msg = "Initialised --"
   }
   
   // Add to the string to be displayed.
   public void start() {
      msg += " Starting --";
   }
   
   // Display the msg in the applet window.
   public void paint(Graphics g) {
      msg += "  Painting.";
      g.drawstring(msg, 10, 30);
   }

When you compile and run it output of this applet will be something like:

Initialised -- Starting -- Painting.

As you will note the methods stop() and destroy() are not overridden, because they are not needed by this simple applet.

Requesting Repainting!

An applet writes to its window only when its update() or paint() methods are called by the AWT. You must be wondering how can the applet, itself, cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? Remember, you cannot create a loop inside paint due the fundamental contraints imposed on an applet - An applet must quickly return control to the AWT run time system. Fortunately the people who designed Java foresaw this predicament and included the repaint() method. Whenever your applet needs to update the information displayed in its window, it simply calls repaint().

The repaint() method is defined by the AWT. It causes the AWT run time system to call to your applet's update() method, which in its default implementation, calls paint(). Again for example if a part of your applet needs to output a string, it can store this string in a variable and then call repaint(). Inside paint(), you can output the string using drawstring().

The repaint method has four forms.

void repaint()

void repaint(int left, int top, int width, int height)

void repaint(long maxDelay)

void repaint(long maxDelay, int x, int y, int width, int height)

Let's look at each one -

void repaint()

This causes the entire window to be repainted

void repaint(int left, int top, int width, int height)

This specifies a region that will be repainted. the integers left, top, width and hieght are in pixels. You save time by specifying a region to repaint instead of the whole window.

void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height)

Calling repaint() is essentially a request that your applet be repainted sometime soon. However, if your system is slow or busy, update() might not be called immediately. This gives rise to a problem of update() being called sporadically. If your task requires consistent update time, like in animation, then use the above two forms of repaint(). Here, the maxDelay() is the maximum number of milliseconds that can elaspe before update() is called.

More Java Resources

If you really followed all I have written above then by now there would be too little blood in your caffine system! But don't despair if you were unable to follow any of the above. Below is a list of books which you will find helpful:

Java 1.1 Developer's Handbook - by Philip Heller and Simon Roberts, Publisher Sybex www.sybex.com

The Java Handbook - by Patrick Naughton (One of the co-developers of Java), Publisher McGraw Hill

Laura Lemay's Java 1.1 interactive Course- by Laura Lemay, Publisher Techmedia, you can take the web based course from www.waite.com/ezone

Next time, we will dig into the innards of the KTN applet which I introduced in my previous article, those of you who feel adventurous enough can take a look at its source code now.

Related items

Steps to Java Internationalization (i18n)

Java Applets in Education

Java #6 I Wanna hold your hand - longer

Mouse Event Handling in Java 1.0

Java #5 I Wanna hold your hand

Java Applets #4

Java Applets #3

Java Applets #1

©2018 Martin Webb