Bruce Eckel's Thinking in Java Contents | Prev | Next

The basic applet

Libraries are often grouped according to their functionality. Some libraries, for example, are used as is, off the shelf. The standard Java library String and Vector classes are examples of these. Other libraries are designed specifically as building blocks to build other classes. A certain class of library is the application framework , whose goal is to help you build applications by providing a class or set of classes that produces the basic behavior that you need in every application of a particular type. Then, to customize the behavior to your own needs you inherit from the application class and override the methods of interest. The application framework’s default control mechanism will call your overridden methods at the appropriate time. An application framework is a good example of “separating the things that change from the things that stay the same,” since it attempts to localize all the unique parts of a program in the overridden methods.

Applets are built using an application framework. You inherit from class Applet and override the appropriate methods. Most of the time you’ll be concerned with only a few important methods that have to do with how the applet is built and used on a Web page. These methods are:

Method

Operation

init( )

Called when the applet is first created to perform first-time initialization of the applet

start( )

Called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ).

paint( )

Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet.

stop( )

Called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ).

destroy( )

Called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used

Consider the paint( ) method. This method is called automatically when the Component (in this case, the applet) decides that it needs to update itself – perhaps because it’s being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method (defined in the base class Component), which goes about restoring everything, and as a part of that restoration calls paint( ). You don’t have to override paint( ), but it turns out to be an easy way to make a simple applet, so we’ll start out with paint( ).

When update( ) calls paint( ) it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because you’re limited to the surface of that particular component and thus cannot paint outside that area, which is a good thing or else you’d be painting outside the lines. In the case of an applet, the surface is the area inside the applet.

The Graphics object also has a set of operations you can perform on it. These operations revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc. (Note that you can look all this up in your online Java documentation if you’re curious.) There are some methods that allow you to draw characters, however, and the most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet’s drawing surface. This location is given in pixels, so it will look different on different machines, but at least it’s portable.

With this information you can create a simple applet:

//: Applet1.java
// Very simple applet
package c13;
import java.awt.*;
import java.applet.*;

public class Applet1 extends Applet {
  public void paint(Graphics g) {
    g.drawString("First applet", 10, 10);
  }
} ///:~ 

Note that applets are not required to have a main( ). That’s all wired in to the application framework; you put any startup code in init( ).

To run this program you must place it inside a Web page and view that page inside your Java-enabled Web browser. To place an applet inside a Web page you put a special tag inside the HTML source for that Web page [54] to tell the page how to load and run the applet. This is the applet tag, and it looks like this for Applet1:

<applet
code=Applet1
width=200
height=200>
</applet>

The code value gives the name of the .class file where the applet resides. The width and height specify the initial size of the applet (in pixels, as before). There are other items you can place within the applet tag: a place to find other .class files on the Internet (codebase), alignment information (align), a special identifier that makes it possible for applets to communicate with each other (name), and applet parameters to provide information that the applet can retrieve. Parameters are in the form

<param name=identifier value = "information">

and there can be as many as you want.

For simple applets all you need to do is place an applet tag in the above form inside your Web page and that will load and run the applet.

Testing applets

You can perform a simple test without any network connection by starting up your Web browser and opening the HTML file containing the applet tag. (Sun’s JDK also contains a tool called the appletviewer that picks the <APPLET> tags out of the HTML file and runs the applets without displaying the surrounding HTML text. [55]) As the HTML file is loaded, the browser will discover the applet tag and go hunt for the .class file specified by the code value. Of course, it looks at the CLASSPATH to find out where to hunt, and if your .class file isn’t in the CLASSPATH then it will give an error message on the status line of the browser to the effect that it couldn’t find that .class file.

When you want to try this out on your Web site things are a little more complicated. First of all, you must have a Web site, which for most people means a third-party Internet Service Provider (ISP) at a remote location. Then you must have a way to move the HTML files and the .class files from your site to the correct directory (your WWW directory) on the ISP machine. This is typically done with a File Transfer Protocol (FTP) program, of which there are many different types freely available. So it would seem that all you need to do is move the files to the ISP machine with FTP, then connect to the site and HTML file using your browser; if the applet comes up and works, then everything checks out, right?

Here’s where you can get fooled. If the browser cannot locate the .class file on the server, it will hunt through the CLASSPATH on your local machine. Thus, the applet might not be loading properly from the server, but to you it looks fine because the browser finds it on your machine. When someone else logs in, however, his or her browser can’t find it. So when you’re testing, make sure you erase the relevant .class files on your machine to be safe.

One of the most insidious places where this happened to me is when I innocently placed an applet inside a package. After uploading the HTML file and applet, it turned out that the server path to the applet was confused because of the package name. However, my browser found it in the local CLASSPATH. So I was the only one who could properly load the applet. It took some time to discover that the package statement was the culprit. In general, you’ll want to leave the package statement out of an applet.

A more graphical example

The example above isn’t too thrilling, so let’s try adding a slightly more interesting graphic component:

//: Applet2.java
// Easy graphics
import java.awt.*;
import java.applet.*;

public class Applet2 extends Applet {
  public void paint(Graphics g) {
    g.drawString("Second applet", 10, 15);
    g.draw3DRect(0, 0, 100, 20, true);
  }
} ///:~ 

This puts a box around the string. Of course, all the numbers are hard-coded and are based on pixels, so on some machines the box will fit nicely around the string and on others it will probably be off, because fonts will be different on different machines.

There are other interesting things you can find in the documentation for the Graphic class. Any sort of graphics activity is usually entertaining, so further experiments of this sort are left to the reader.

Demonstrating

the framework methods

It’s interesting to see some of the framework methods in action. (This example will look only at init( ), start( ), and stop( ) because paint( ) and destroy( ) are self-evident and not so easily traceable.) The following applet keeps track of the number of times these methods are called and displays them using paint( ):

//: Applet3.java
// Shows init(), start() and stop() activities
import java.awt.*;
import java.applet.*;

public class Applet3 extends Applet {
  String s;
  int inits = 0;
  int starts = 0;
  int stops = 0;
  public void init() { inits++; }
  public void start() { starts++; }
  public void stop() { stops++; }
  public void paint(Graphics g) {
    s = "inits: " + inits + 
      ", starts: " + starts +
      ", stops: " + stops;
    g.drawString(s, 10, 10);
  }
} ///:~ 

Normally when you override a method you’ll want to look to see whether you need to call the base-class version of that method, in case it does something important. For example, with init( ) you might need to call super.init( ). However, the Applet documentation specifically states that the init( ), start( ), and stop( ) methods in Applet do nothing, so it’s not necessary to call them here.

When you experiment with this applet you’ll discover that if you minimize the Web browser or cover it up with another window you might not get calls to stop( ) and start( ). (This behavior seems to vary among implementations; you might wish to contrast the behavior of Web browsers with that of applet viewers.) The only time the calls will occur is when you move to a different Web page and then come back to the one containing the applet.


[54] It is assumed that the reader is familiar with the basics of HTML. It’s not too hard to figure out, and there are lots of books and resources.

[55] Because the appletviewer ignores everything but APPLET tags, you can put those tags in the Java source file as comments:

// <applet code=MyApplet.class width=200 height=100></applet>

This way, you can run " appletviewer MyApplet.java " and you don’t need to create tiny HTML files to run tests.

Contents | Prev | Next