Chapter 37

Writing Java Applets

by Rick Darnell


CONTENTS

Sun Microsystems defines Java as, "a simple, robust, secure, object-oriented, platform-independent, dynamic programming environment." At first, all of this Java talk can sound like a lot of voodoo. After you strip away the hype, however, it's easy to see how Java works effectively for implementing simple solutions to potentially complicated challenges in a distributed environment.

What Does the Java Language Offer?

Going back to Sun's description, Java is a language designed to make programming an easier task by hiding the parts which are best handled on a platform-specific basis, and modeling the rest after the way people think. Here's a quick breakdown.

Simple

Java has been designed with C and C++ programmers in mind. C and C++, however, had many hard-to-understand, rarely used features that the Java developers felt caused more pain than benefit. Important functions that come standard to every program, such as memory allocation and pointer arithmetic, automatically get handled by the Java system without needing any acknowledgment from the programmer.

In addition, Java is relatively small. Because of the need to run on a wide variety of platforms, Java applications tend to be smaller than the multi-megabyte applications that dominate the marketplace. The overhead to run a Java program includes 40 K for the basic interpreter and classes, plus an additional 175 K for the standard libraries and threading.

Robust

Java programs must be inherently reliable because any piece of Java byte must be capable of running on any platform. For this reason, a great deal of emphasis gets placed on checking for bugs and problems early in the development process, beginning with basic language implementation.

Use of pointers is a popular example. C++, a close cousin of Java, uses extensive arithmetic to keep track of arrays and other memory variables. This setup enables programmers to take full advantage of a specific platform, but it also creates problems when pointers go awry, overwriting memory and corrupting data. It also prevents a program developed for a Windows environment from working on a UNIX platform.

The Java compiler checks for a wide variety of errors beyond basic syntax, including type casting and method invocations. If you've made a mistake or mistyped, chances are good that your mistake gets flagged by the compiler, which is a far better place than by the interpreter at run time.

Object-Oriented

Object-oriented, probably one of the most overused and confusing terms in computer lingo, really has a simple and easy-to-understand meaning. It facilitates creating clean and portable code by breaking software down into coherent units. Objects become the basic building blocks of the application. Because of their modularity, an object can change without requiring major revision to the other program elements.

Getting The Tools You Need

The first item needed for writing applets is the Java Developer's Kit. This includes a compiler, interpreter, and the classes which are the building blocks of Java applets and applications. You can find the Java Developer's Kit (JDK) on the JavaSoft site at http://java.sun.com/.

Note
For more information on the differences between Java applications and applets, see Chapter 36, "Including Java Applets in Your Web Pages."

The JDK is a bare-bones resource. It only includes the absolutely essential items to make Java run, plus a handful of applets and the AppletViewer. To create applets, use your favorite text editor or word processor. The only requirement is that it saves your work in a standard text format with a .java extension.

In addition to the JDK, there are several other tools available to make developing applets easier.

JavaPad

JavaPad is a simple shareware program for Windows which makes developing Java applets and applications much easier. It includes a text editor for creating the applet source code, and the ability to run your stand-alone application or the AppletViewer.

After you save the .java file, JavaPad links to the Java compiler and generates a class file. If there are compiling errors, they're listed in a separate window where you can step through and correct each deficiency (see Figure 37.1).

Figure 37.1 : JavaPad is a simple and useful program for building Java applications.

Although a bare-bones application, JavaPad is a very friendly way to get started with development software. Its home page is www.modelworks.com/express/.

Symantec Café

Symantec Café is one of the first integrated development environments produced for Java. It includes all of the features needed by professional programmers, including version control and project management. It also includes an interface editor and graphical debugger. It is available for Windows and Macintosh. More information on ordering or downloading is located at cafe.symantec.com.

Sun Java Workshop

Another option is the Java workshop, created by the Java developers. It is every bit the rival of Symantec Café, only available in shareware form. If it has a drawback, it's that it doesn't include a faster compiler than Café, but in every other regard it's a high-quality application and well worth the download time to try. More information on features and availability is located at www.sun.com/developer-products/java/.

Creating Java Applets

Creating Java applets is easier if you already have a background in programming. With Java's tight structure, the basic format of an applet is fairly straightforward. You walk through an example here.

Tip
You can access online tutorials and documentation for Java and object-oriented programming from the Sun site, http://java.sun.com/.

An Object and Class Primer

Java is object-oriented, meaning that Java programs are built out of sections of code which package data with the instructions that affect it. A class is the template from which objects are created.

Think of it as a suburban neighborhood of cookie-cutter tract houses. All of the houses begin as a blueprint, and every house uses the same one. But you can't live in a blueprint, so you have to put the concrete, lumber, pipes, wire, and drywall together to build a house. In Java, this is called instantiation, and an instance of the blueprint is called an object. Many houses (objects) are built from the same blueprint (class).

Applet ABCs

At its simplest, an applet consists of two parts-the class declaration and a paint method. The following snippet contains a breakdown of the common elements for any applet:


import java.awt.Graphics;



public class MyApplet extends java.applet.Applet {

    public void paint (Graphics g) {

       your statements here;

    }

}

The first line includes a copy of the Graphics class from Java's Abstract Windowing Toolkit (AWT), which contains the methods needed for putting graphics, including text, lines, and dots, on the browser screen. This line may also be represented as import java.awt if more than the Graphics class is used.

Secondly, the applet is declared. It is public, meaning it is available to any other class, and it is a subclass of Java's Applet class, which provides the behavior necessary for interaction with the host browser.

The third section defines a method called paint, which the Java interpreter looks for to put the information on the screen. It is public to the class, and void indicates it does not return a value when it is completed. Its one parameter is an instance of the Graphics class imported on the first line of the program, which is referred to as g. This reference can as easily be called bob or hammer, but g is the commonly used convention.

Displaying with the Paint Method

Now that the applet is defined, you need to make it do something. For the paint method, include the following line.


g.drawString("Hava a nice day.",50,25);

After compiling the code and inserting it into an HTML document, you get something that looks like Figure 37.2.

Figure 37.2 : MyApplet displays a simple message on the screen.

Note
For more information on including applets in your Web page, see Chapter 36, "Including Java Applets in Your Web Page."

Tip
To convert your source code into a usable class, type javac MyApplet.java at the command prompt to invoke the Sun JDK compiler. If you're using a third-party compiler, follow the instructions provided with it. If any errors are reported, check your spelling and syntax and try again. If the system can't find the Java compiler, make sure its location is included in the system's execution path.

Tip
To test your applet you can use a browser such as Netscape Navigator (2.0 or later) or Microsoft Internet Explorer (3.0 or later). Another alternative is the Java AppletViewer, which is provided with the Java Developer's Kit. For more information, see "Using the Java AppletViewer," later in this chapter.

Of course, applets can do much more. By including some other AWT classes, the text can look better. First, you need the classes that control the font and display color.


import java.awt.Font;

import java.awt.Color;

Now, after the class declaration, create a variable to hold a new setting for the text.


Font f = new Font("TimesRoman",Font.ITALIC,24);

After the paint method declaration, use the Graphics.set methods to set the display before writing to the screen.


g.setFont(f);

g.setColor(Color.red);

With this extra bit of effort, the applet now looks like Figure 37.3.

Figure 37.3 : MyApplet now displays in a larger font in red after some minor revisions to the code.

Again, this example is limited. The addition of a parameter to control the string makes it more useful to the HTML author. After the class declaration, declare the message as a variable.


String message;

A new method is also required to initialize the value of message.

Applet activities
In addition to paint, four major activities exist in the life of an applet. If any get omitted, default versions are provided in the Applet class. This setup is called inheritance. Providing new methods in the applet is called overriding.
The first activity is initialization, accomplished with the init method: public void init() {...}. This activity occurs once, immediately after the applet is loaded. Initialization includes creating objects, setting graphics, or defining parameters. It can only happen once in the applet's life.
The second activity is starting, accomplished with the start method: public void start() {...}. After initialization, activity begins. This activity can also happen if a user activity stopped the applet. Starting can happen many times in the life of an applet. The paint method gets invoked somewhere in this method.
The next activity is stopping, accomplished with the stop method: public void stop() {...}. This activity can be an important method to include because by default the applet continues running and using system resources, even after the user has left the page with the applet. Like start, stopping can occur many times in the course of execution.
The last activity is destroying, accomplished with the destroy method: public void destroy() {...}. Destroying is where an applet throws out its own garbage after completing execution-when the applet is no longer needed or the user exits the browser. Java provides adequate coverage in this department, so you don't need to override this method unless you want to return specific resources to the system.

Initializing the message parameter requires overriding the init method for the applet.


public void init() {

    this.message = getParameter("message");

    if (this.message == null) {

        this.message = "Your message here."; }

    this.message = "A note from Java: " + this.message;

}

This method retrieves the value of the parameter in the HTML document. If a parameter named message is not found, then the value is null and message is set to the default string, Your message here.

Note
Java is case-sensitive for all of its variables, even when passed back and forth as parameters. Remember, Bob doesn't bob.

Now you need to update the paint method so that it uses the string defined in init, rather than the literal string in the drawString method.


g.drawString(this.message);

Using the AppletViewer again now generates the results in Figure 37.4.

Figure 37.4 : The default message generated by MyApplet, after checking for a message parameter and finding none.

To place your own message in the applet, add a <PARAM> tag to the HTML source containing the applet. For more information, see "Passing Parameters," later in this chapter. The complete listing for MyApplet appears in Listing 37.1. Note the use of the parameter in the init method.

Tip
Listing 37.2 is a sample HTML file which can be used as the basis for inserting or testing applets. Saved in a generic form, it is a very handy and reusable piece of code.

Tip
The file name for the source code must match the name of the applet, including capitalization. Java is case-sensitive in everything it does, including compiling and creating class files.


Listing 37.1. A simple applet for displaying text onscreen.

import java.awt.Graphics

import java.awt.Font;

import java.awt.Color;



public class MyApplet extends java.applet.Applet {

    Font f = new Font("TimesRoman",Font.ITALIC,24);

    String message;



    public void init() {

        this.message = getParameter("message");

        if (this.message == null) {

            this.message = "Your message here."; }

        this.message = "A note from Java: " + this.message;

    }



    public void paint(Graphics g) {

        g.setFont(f);

        g.setColor(Color.red);

        g.drawString(this.message,50,25);

    }

}



Listing 37.2. A sample of an HTML document that can display MyApplet.

<HTML>

<HEAD>

<TITLE>The MyApplet</TITLE>

</HEAD>

<BODY>

<HR>

<APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=50>

<PARAM NAME=message VALUE="Here I am.">

</APPLET>

<HR>

</BODY>

</HTML>


Interacting with the User

OK, all the little messages on the screen are neat, but how about actually doing something? The mouse is the preferred weapon on the World Wide Web, so we'll start with reacting to a user doing things with the mouse, beginning with a mouse click.

Looking for a Click

Java divides a mouse click into two parts, mouseDown when the button is depressed and mouseUp when it's released. This may seem like micro-management, but it's really quite useful.

Think of a drop-down menu. Click and hold to view the menu, and then drag the mouse down to your choice and release the button to select it. In Java, the mouseDown indicates the menu is selected and the items are displayed and mouseUp indicates a selection is made.

Mouse events are handled by overriding the default method for the particular action. The general syntax follows this example:


public boolean mouseDown(Event mdEvent, int x, int y) {

...stuff to do...

}

The method returns a Boolean value, true when the button is down, and false when it's up. Its first parameter is the actual event, which is itself an instance of a class. All system events generate a new instance of the Event class, which includes information on the type of event, where it happened, and when it took place. This provides a way to grasp the event and preserve it until your applet processes it. The next two parameters are the screen coordinates of where the event occurs.

A simple way of viewing this activity is to include the following two methods in your applet.


public boolean mouseDown(Event mdEvent, int x, int y) {

    System.out.println("Click at " + x + ", " + y);

    return true;

}

public boolean mouseUp(Event muEvent, int x, int y) {

    System.out.println("Release at " + x + ", " + y);

    return true;

}

Note
The coordinates relate to the space occupied by the applet only. An event object is not created for activities outside of the applet.

Note the last line in both methods, return true. This value is used so that other parts of the user interface can work with the event if it needs to. A good rule of thumb is that the event method should return true if it's your method that works with it.

Now, let's use this information for a little target practice. The TargetShoot applet shown in Listing 37.3 looks for a mouseDown event, and places a small circle on the screen where it occurs. It gives you the chance to hit the target six times (Figure 37.5).


Listing 37.3. The TargetShoot applet.

import java.awt.Graphics;

import java.awt.Color;

import java.awt.Event;



public class TargetShoot extends java.applet.Applet {

    final int shots = 6;

    int xhit[] = new int[shots];

    int yhit[] = new int[shots];

    int shotsTaken = 0;



public void init() {

    setBackground(Color.white);

}



public boolean mouseDown(Event mdEvent, int x, int y) {

    if (shotsTaken < shots)

        bang(x,y);

    else System.out.println("Out of bullets.");

    return true;

}



public void bang(int x, int y) {

    xhit[shotsTaken] = x;

    yhit[shotsTaken] = y;

    shotsTaken++;

    repaint();

}



public void paint(Graphics g) {

    g.setColor(Color.red);

    for (int i = 0; i < shotsTaken; i++) {

        g.fillOval(xhit[i] - 10, yhit[i] - 10, 20, 20);

    }

}



}


Figure 37.5 : The TargetShoot applet places a small red dot on the screen every where the user clicks.

Here's what's happening with the applet. The variables which store the maximum number of shots and the current number of shots taken are initialized, along with an array to hold the x and y positions of each one. The mouseDown method is used to call the bang method when the mouse button is clicked. The bang method records the location of the shot and calls the repaint method to update the screen. The last method, paint sets the color of the hits to blue and paints a circle at each of the locations where a shot has been taken.

Pressing Some Keys

Java can also look for keyboard activity using the keyDown method. The syntax of the method is similar to the mouse events.


public boolean keyDown(Event kEvt, int key) {

...

}

Like the other user input events, keyDown needs an event variable as one of its parameters. But instead of x and y coordinates for the location of the event, it accepts an ASCII value representing the key. If you want to turn the value into the actual character, use char casting method.


theCharacter = (char)key;

As part of the Event class, a set of key names are provided to make it easier to write code for items like the arrow and directional keys. Table 37.1 lists these key names.

Table 37.1. Key names in the Event class.

Event.PropertyfKey
Event.HOME Home Key
Event.END End Key
Event.PGUP Page Up Key
Event.PGDN Page Down Key
Event.UP Up Arrow
Event.DOWN Down Arrow
Event.LEFT Left Arrow
Event.RIGHT Right Arrow

The next task is to display characters on the screen in response to the keyboard. Whatever key the user presses appears on the screen (see Figure 37.6), and pressing the page down key clears the screen. Listing 37.4 provides the code for this task.


Listing 37.4. The KeyPress applet uses the same Event class used by the TargetShoot applet.

import java.awt.Graphics;

import java.awt.Event;

import java.awt.Font;

import java.awt.Color;



public class KeyPress extends java.applet.Applet {

    char currentKey;

    int valueKey;



public void init() {

    setBackground(Color.white);

    setFont(new Font("TimesRoman",Font.ITALIC,24));

}



public boolean keyDown(Event keyEvent, int key) {

    valueKey = key;

    switch (key) {

    case Event.PGDN:

        setBackground(Color.white);

        currentKey = 0;

        break;

    default:

        currentKey = (char)key;

    }

    repaint();

    return true;

}



public void paint(Graphics g) {

    switch (currentKey) {

    case 74:

        g.drawString("JAVA", 20, 30);

        break;

    case 106:

        g.drawString("java", 20, 30);

        break;

    case 0:

        g.drawString(" ", 20, 30);

        break;

    default:

        g.drawString(String.valueOf(currentKey)+" is ASCII: "+valueKey, 20, 30);

    }

}



}


Figure 37.6 : The KeyPress applet displays the character pressed and its ASCII value except for upper and lowercase j, when it prints Java.

For the most part, this is a straightforward operation. When a key is pressed, the keyDown method checks to see which key is pressed. If it's the page down key, the screen is cleared and nothing is displayed. Otherwise, the value of the key is passed to currentKey.

There are a few items included in this applet which are new. First, notice the two uses of the switch control. This is in effect a large if-then statement. The variable to compare is included in the first line, followed by a series of case statements with values. If the variable in the switch statement matches the value in the case statement, the set of instructions under it are executed. But there's a small hitch.

Normally, once the statements under the specific case are completed, execution passes to the next case statement in line. This isn't what we want, and so a break command is placed at the end of each case. When the program reaches the break, control is passed to the end of the entire switch. The last line of each switch is the optional default. This default is used to guarantee a certain behavior if a match is not found within any of the cases. Because it's the last item, a break isn't needed.

Working with Images

Loading and displaying images in Java is an easy task, thanks to the Image class located in java.awt. The first method to work within Image is getUmage, which loads the image from the Internet to your applet.

Note
Images are not integrated with the applet. Currently, Java only supports gif and JPEG image files.

To load the image file, getImage needs to know where to find it. There are two ways of doing this:

Although the first method appears to be much simpler, it is not very flexible. If the location of the image changes, you have to change the source code and recompile the applet.

The second form is the preferred method, and includes two options for establishing the base URL:

But as it's said, a picture's worth a thousand words, so here are a few examples of how getImage works:

It's important to note that at this point the applet has only loaded the image, it hasn't done anything with it. It only exists as an Image object called pict. Now it's time to display it using a method from the Graphics class.


public void paint(Graphics g) {

    g.drawImage(pict,10,10,this);

}

Note
You may have noticed the this parameter in the drawImage method. Its function is to draw the file contained in the object that calls the method. The this parameter always refers to the host object.

That's all there is to it. This form of drawImage displays pict with the top left corner at the coordinates 10,10. You can also add a second set of numbers to define the width and height of the image when it's painted, enabling you to make it fit anywhere you want.

Tip
Expect image degradation when you expand or contract an image very far beyond its original size. Changing the height to width ratio also distorts the image.

The entire applet to display the image (Figure 37.7) is shown in Listing 37.5. The Animator applet uses these basic operations to display a series of images that gives the appearance of motion.


Listing 37.5. A simple applet to load and display an image.

import java.awt.Graphics;

import java.awt.Image;



public class showPict extends java.applet.Applet {



Image pict;



public void init() {

    pict = getImage(getCodeBase(),"images/garden.gif");

}



public void paint(Graphics g) {

    g.drawImage(pict,10,10,this);

}



}


Figure 37.7 : The showPict applet loads an image from the images subdirectory of the javaApplets directory.

Using the Java AppletViewer

During applet development and testing, sometimes it's easier to bypass the unnecessary overhead of a browser. If your browser doesn't support applets, you still need a way to view the applets. At this point, the Java AppletViewer (see Figure 37.8) comes in handy.

Figure 37.8 : The Java AppletViewer enables the programmer to view embedded Java applets without the use of a browser. Only the applet is displayed. The rest of the HTML is ignored.

The AppletViewer searches the HTML document for the <APPLET> tag, such as the one shown in Listing 37.6. Using the information contained within the tag, it opens a window and runs the applet. Other HTML information on the page is ignored-only the applets appear.


Listing 37.6. A simple HTML document containing an <APPLET> tag.

<HTML>

<HEAD>

<TITLE>The animation applet</TITLE>

</HEAD>

<BODY>

<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160>

<PARAM NAME=imagesource VALUE="images/beans">

<PARAM NAME=endimage VALUE=10>

<PARAM NAME=pause VALUE=200>

</APPLET>

</BODY>

</HTML>


The Java AppletViewer is distributed with the Java Developer's Kit and is found in the same directory as the Java compiler and interpreter. To run the AppletViewer, use the following steps:

  1. Create a document that references your applet with the appropriate tags and parameters. See Listing 37.6 for an example.
  2. From a command line prompt, type appletviewer [path/]filename.html.
  3. If the AppletViewer launches from the same directory as the HTML document, you don't need the path name. Otherwise, the path is relative to your current location in the directory structure. The extension .htm is also valid for the viewer.
  4. Any applets found in the HTML document are loaded and run, with each applet in its own instance of the AppletViewer.
  5. Although you cannot change the initial parameters contained within the HTML page from the AppletViewer, you can start the applet from the beginning by choosing Applet | Restart. To load it again from memory, select Applet | Reload.
  6. Leave the applet by choosing Applet | Quit.

Tip
The AppletViewer Reload function does not work if the application has been launched from the same directory as the HTML document and classes. For applets, create a subdirectory from your class directory called HTML, and place all of your classes and HTML files in it. Call the AppletViewer from the parent directory by using appletviewer html\filename.html. This way, you can make changes to the applet, compile it, and use the Reload function to see your changes.

Java Resources on the Web

As a language and as a way of thinking which has found its fame and fortune on the World Wide Web, the Internet remains the primary source of information and tools to learn more about Java. Here are a few of the high spots you may want to look at.

JavaSoft

(http://java.sun.com/)

JavaSoft, a subsidiary of Sun Microsystems, is the leading figure in the continuing evolution of Java and Java products. Go to their Web site (see Figure 37.9) first when looking for information, documentation, development kit updates, applet downloads, and other feedback. Originally part of the Sun Microsystems Web site, JavaSoft has been created to handle the dramatic increase in attention Java has received since its release.

Figure 37.9 : The JavaSoft home page includes links to the Java Developer's Kit, HotJava, and other information of use to Java developers.

JavaWorld

(http://www.javaworld.com/

The first online publication devoted entirely to Java, JavaWorld (see Figure 37.10) is a monthly publication which includes hands-on tips and tricks. A programming contest, "Applet of the Month," is a regular feature. Other articles include links to source code and other helpful items.

Figure 37.10: Java World includes interviews with the movers and shakers in the Java realm, along with hands-on examples, tutorials, and contests.

alt.lang.java

Although not technically a source for applets, the alt.lang.java newsgroup provides a great source of information about Java and its uses. Following the threads can also lead to Java applets and applications, where you can learn from people already making the most of this new language.

Summary

What I've offered on Java in this chapter is a teacup compared to the big coffee machines at Starbuck's. This chapter should have given you an idea of how applets are put together and what tools and methods are used within them to make the applet do something on the Web page.

There's a slew of books available on Java, and more are popping up every day. A good place to get your feet really wet is Teach Yourself Java in 21 Days by Laura Lemay and Charles Perkins.

But for now, there's one more ability you can quickly add to your toolkit of Web publishing tools-communication and interaction between JavaScript and Java. The next chapter shows you how to access your applet's methods from JavaScript and how to retrieve information about your Web page from Java using the latest capabilities.