Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Java Developer's Reference

Chapter 7 -- Developing Java Applets

Chapter 7

Developing Java Applets


CONTENTS




This chapter focuses on the development of a type of Java program known as an applet. Chapter 8, "Developing Java Applications," discusses the development of Java applications. Although there are some inherent differences between an applet and an application, many beginning developers are unaware of these differences. After explaining exactly what an applet is, this chapter will present the Java applet in more detail. By the end of the chapter, the Java developer should have a good knowledge of the Java applet security model, the Java applet life cycle, and basic applet capabilities such as multithreading and I/O.

What Is an Applet?

Java applets are actually compiled Java class files that are run on a page within a Web browser. Because the Web browser supplies the framework for retrieving and loading an applet and also supplies the main window holding the applet, Java applets are somewhat simpler than a true Java application. A Java application does not require any additional software, such as a Web browser, other than the typical Java runtime files included in the Java Developer's Kit. Java applications are designed to be run in stand-alone mode on a client machine and therefore can be thought of as a known entity. Java applets, meanwhile, can be loaded from anywhere on the Internet, and therefore are subject to severe security restrictions. These security restrictions will be discussed in greater detail later on in this chapter.

Almost every person's first exposure to Java was in the form of a Java applet running within a Web page. Java applets currently are being used for advertising purposes because they provide the capability to include simple animation and sound in a Web advertisement. Many client/server developers currently are looking at the company intranet as an excellent platform on which to finally deliver true cross-platform corporate applications. Because of this, Java applets are certain to quickly progress from "neat" status to true business use status.

What Is Required to Run an Applet?

Java applets are typically run within a Web browser. As of July 1996, most of the popular Web browsers on the market support embedded Java applets in HTML pages. These browsers include:

Of course, the Applet Viewer tool included with the Java Developer's Kit can be used to test and run Java applets as well. However, it will not be included on all client machines; therefore, it is not really an option to applet developers. Many beginning Java developers wonder how an applet can run within a browser if the Java runtime libraries are not installed on the client system. To run a simple Java applet, as explained in Chapter 2, "Installing Java," it was first necessary to download the JDK from the JavaSoft Web site. After installing the JDK on the system, the reader could then run any sample Java applet included with the JDK. However, someone installing the Netscape Navigator, for instance, has not downloaded the JDK, right? In fact, they partially have. Take a look at the actual Navigator installation to find out what was actually placed on your system.

After installing Navigator 3.0 in the C:\Program Files\Netscape\Navigator directory, examine the contents of that directory under Windows 95. Under the .\Program\java directory, you will find a set of directories and files that look suspiciously like the JDK installation. This is how Web browsers are able to run Java applets. They basically install a customized version of the JDK in their runtime directories so that they can load Java applets and their own set of customized Java classes. This results in somewhat of a Catch-22 situation. Because Netscape, for instance, provides a customized version of the JDK, subtle changes in the underlying code could result in an applet running differently in the Navigator browser than, say, the Internet Explorer browser. Be sure to test completed Java applets in a wide variety of browsers on a variety of operating systems, if possible, in order to ensure that the applet you will be displaying to the world does what you think it should.

Capabilities and Limitations of Applets

Java applets obviously have many potential capabilities. Many things can be done using these applets that, until now, were impossible to implement on such a broad scale. Java applets can be used to build full-featured graphical user interfaces, communicate over the Internet to a host server, and even communicate with other applets on a form. All of this can be done in an operating-environment-neutral manner, which is what makes this such a great technology. For Java to be truly successful, however, the client security has to be completely assured. Because of this, security measures place some limitations on Java applets. By default, applets cannot communicate with any server other than the originating server. Applets also cannot read or write files to the local file system. The following section discusses the Java security model and focuses on how this applies to Java applets.

The growth of technologies such as Web-based client/server application development and electronic commerce has been severely limited by the lack of "industrial-strength" security. Because the underlying Internet was never designed to handle secure transactions (the Department of Defense has a separate net for this purpose), the entire infrastructure of the Internet was somewhat unprepared for the phenomenal growth of the World Wide Web over the last few years. The concept of applets (or related technologies such as software agents) has been discussed in academic circles for years, yet most theoreticians realized the security shortcomings of the current programming languages such as C and C++.

Programming languages that allow manipulation of pointers (memory addresses) allow programmers to overrun memory boundaries and find "trap doors" into unsuspecting users' systems. Operating systems such as UNIX have continually struggled to patch well-documented security holes. Because the designers of Java were well aware of these problems, security measures were designed into Java at nearly every layer. The Java language's lack of support for pointers also leads to simpler, easier-to-read code. (Many programming errors by C programmers can be traced to improper manipulation of pointers to memory.)

The basic security model for Java treats all Java applets and applications as unknown, unsecured objects running within a secure environment. What this means is that a clever developer can produce subversive code to his heart's content, but the underlying Java runtime environment is designed to trap any problems. When the media publicizes a Java security "bug," this generally means that a team of researchers isolated a security flaw in the underlying runtime environment that hackers could capitalize on. An example of an early Java bug allowed a Web server to track all Web sites a user visits after the Web server itself has been visited. Although Java applets will never be used in the near future to implement truly secret applications, the Java security model makes security exceedingly difficult to circumvent.

The Java designers handled security at three levels:

Bytecode Verification

Language security features are simply not enough to prevent an applet from reformatting your hard drive or some other unspeakable act. (Keep in mind that file I/O is allowed and even provided using the JDK class libraries.) Features needed to be built into the entire runtime system to prevent specially compiled applets from invading remote systems. Java is an interpreted language. This means that actual memory management for the application is put off until runtime (it is not built into the compiled Java classes). This feature allows Java to run on many different platforms thanks to the installed Java Virtual Machine. However, it also allows the Java runtime engine to verify that the bytecodes being loaded are, in fact, good bytecodes. This is done using a part of the Virtual Machine known as the verifier. The verifier has the unenviable task of checking each bytecode before it is executed (interpreted) to make sure that it is not going to perform an illegal operation. After the bytecode has been verified, the applet is guaranteed to do the following:

The verification process checks many of the things that a good Java compiler will check, but it is important to recognize that the verification process takes place on the client's computer. Security on the server side is virtually meaningless to Internet clients because of the unknown nature of most servers.

Client-Side Precautions

The set of precautions enforced by the client Web browser (or other applet loader) is done by a part of the Java runtime engine known as the class loader. The class loader does what its name says: it loads classes.

Note
The class loader can vary from browser to browser. Security features in the HotJava web browser allow the user to control security restrictions and even remove them altogether. The Netscape Navigator browser, however, offers no user-controlled security measures. Instead, applets are forced into a very rigid set of rules. Therefore, it is probably wise if applets are written to conform to the most restrictive case because then they will run on every user's computer.

Three possible worlds are recognized by the class loader:

The class loader implements defined rules that allow it to intelligently prevent an applet from wreaking havoc on your system. It does this by never allowing a class loaded from a lower level to replace a class existing on a higher level. The following example illustrates what this means.

An applet located on a Web server across the Internet imports the java.awt.Button class so that it can display a button on the screen. The developer on the remote machine changed some of the button's internal functionality but kept the class interface without changing anything. Fortunately for you (and unfortunately for the developer across the Internet), the java.awt.Button class is included with the Java Virtual Machine installed on your system. Therefore, when the applet is uploaded to your machine, the class loader will always retrieve your local Button.class file.

In addition to this, classes cannot call methods from other classes in other security levels unless those methods are explicitly declared to be public. This means that Java applets loaded from a remote machine cannot call file system I/O methods. If those methods were called, the class loader would catch the error, and the applet load would fail.

Java Class Loading Rules (Example1.html)

Although much of the information presented on Java has stated that applets cannot write to a local hard drive or connect to remote computers other than the originating host, this is in fact not necessarily correct. The HotJava Web browser allows users to configure these security restrictions (see Figure 7.1).

Figure 7.1 : The Java applet security screen in HotJava 1.0.

Figure 7.1 shows how the HotJava user can loosen or even drop all security restrictions so that applets can do whatever they want when uploaded to his or her machine. This may be useful in an intranet setting where machines are never connected directly to the Internet, but be very careful otherwise. Undoubtedly, devious applets will be written to do damage to unsuspecting systems. This is why the Netscape Navigator developers left configurable security features completely out of their product.

Are Java Applets Safe?

Java handles security at several different levels. The language is designed in a manner that removes many security holes because it does not allow pointer manipulation. The bytecode verifier is used to verify each uploaded Java class to ensure that it obeys all Java language rules. The class loader enforces security on another level by controlling applet operations at runtime. It is important to realize that the bytecode verifier and class loader both exist on the local system and are part of the Java Virtual Machine. Because these two components are critical to the success of the Java security model, the user must rely on these components to ensure that Java applets are secure. At the current time, Sun, Netscape, Microsoft, IBM, and others are all working on implementations of the Java Virtual Machine for a host of operating platforms. As the number of "third-party" virtual machines increases, it is critical that these virtual machines be verified by some independent source to ensure that they operate according to the JVM specification. Sun is currently working on a test suite to do just this. In short: Yes, the Java environment is safe and secure. Vendor-specific implementations, however, must be validated to ensure that they comply with the Java specifications.

Building a Java Applet

This section focuses on the construction of Java applets. The previous section discussed in some detail the process required to load an applet over the Internet to the local machine, and this section will explain what is necessary for the applet to actually run on that local machine.

Java applets are subclassed from the Applet class in the java.applet package.

Note
For more information on subclassing, see Chapter 3, "The Java Language." For more information on the java.applet package, see Chapter 27, "Package java.applet."

Each applet has four major events in its lifetime:

These four events correspond directly to four methods within the Applet class: init(), start(), stop(), and destroy(). The following discussion provides some information on each of these methods.

public void init()
The init() method is called when the applet is initially loaded. This method is used to do one-time setup features such as add components to the layout manager, set screen colors, and connect to a host database.
public void start()
The start() method is called after the applet has been initialized, and also each time the applet is restarted after being stopped. Applets can be stopped when the user changes to another Web page. If the user returns at a later time to the page with the applet on it, the applet will be restarted by the browser. Therefore, the start() method can be called many times during an applet's life cycle. Common operations that occur during an applet's start() method are the initialization of threads within the applet and the updating of the screen display.
public void stop()
The stop() method is called whenever the user leaves the current page. Note that by default when the user leaves a page, the applet will continue to run. This can result in an enormous consumption of system resources if many applets have been loaded and these applets are performing some resource-intensive task such as animation. (In fact, it is quite common to see poorly written applets loaded from the Internet that obviously did not implement this method. They never stop running!) The stop() method is used to temporarily suspend the execution of the applet until the start() method is called again.
public void destroy()
The destroy() method is called whenever it is time to completely finish the applet's execution. This method is generally called when the browser is exiting or the applet is being reloaded from the host server. The destroy() method is used to free up allocated resources such as threads or database connections.

Listing 7.1 shows a simple applet that implements all four life cycle methods: init(), start(), stop(), and destroy(). This applet updates the screen as well as the browser status bar with some information indicating which method is being called.


Listing 7.1. An applet illustrating the life cycle methods.
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;

public class LifeCycleApplet extends java.applet.Applet
{
  Font theFont = new Font("Helvetica", Font.BOLD, 20);
  int  i;
  String String1, String2;

  public void paint(Graphics g)
  {
    g.setFont(theFont);
    g.setColor(Color.blue);
    g.drawString(String1 + String2, 5, 30);
  }

  public void init()
  {
    i = 0;
    String1 = "";
    String2 = "The applet is initializing!";
    repaint();
    showStatus("The applet is initializing!");
  }

  public void start()
  {
    i = 1;
    String1 = String2;
    String2 = "The applet is starting!";
    repaint();
    showStatus("The applet is starting!");
  }

  public void stop()
  {
    i = 2;
    String1 = String2;
    String2 = "The applet is stopping!";
    repaint();
    showStatus("The applet is stopping!");
  }

  public void destroy()
  {
    i = 3;
    String1 = String2;
    String2 = "The applet is being destroyed!";
    repaint();
    showStatus("The applet is being destroyed!");
  }
}

The previous example will always show the last two life cycle events on the screen. Because of the speed at which Java executes, you were probably unable to see the init() method's results all by themselves. We could have added a counter loop just to stall the applet, so feel free to do so if you're interested. Using threads, we also could have called a wait() method to stop program execution for a specified amount of time. However, threads are a topic for a later time (see Chapter 20, "Working with Threads"). Figure 7.2 shows the LifeCycleApplet loaded into a Web browser using the Example2.html file.

Figure 7.2 : Example2.html containing the LifeCycle applet.

HTML and Java Applets

The last example took advantage of a file named Example2.html to display the applet within a Web browser. The actual Java code used to display the applet was examined in the last section, but you may be wondering where the additional text on the screen came from. Currently, Java applets can only be displayed within a Web browser by being embedded in a standard HTML page. This does not mean that the actual bytecode or source code of the applet is included within the HTML file. Instead, the HTML text contains a reference to the Java applet known as a tag. Each element within an HTML file to be displayed by a Web browser is referenced using different types of these tags. Listing 7.2 shows the contents of the HTML file used to load the LifeCycleApplet applet.


Listing 7.2. The Example2.html file contents.
<HTML>
<HEAD>
<TITLE>This is the LifeCycle applet!</TITLE>
</HEAD>
<BODY>
<H1>Prepare to be amazed!</H1>
<BR>
<APPLET CODE="LifeCycleApplet.class" WIDTH=600 HEIGHT=50>
If you can see this, your browser does not support Java applets.
</APPLET>
</BODY>
</HTML>

Note
This chapter is not intended to be an HTML tutorial. For much more information on HTML and Java, see Chapter 12, "HTML for Java Programmers."

A quick examination of Listing 7.2 shows three primary elements:

If you are new to HTML, the most important point to realize is that nothing in this file specifies actual screen layout. The TITLE tag, for instance, does not specify that the title appear at (x,y) coordinates (150, 200) and that it should be set apart from the heading by ¨". HTML only specifies the markup that tells browsers what information to display. The page designer is somewhat at the mercy of Web browser developers, although keep in mind that it is in the best interest of browser developers to provide a standardized "look-and-feel" to most Web pages. It is still common, however, to load pages side by side in Netscape Navigator and Microsoft Internet Explorer and notice slight layout differences. Fortunately, for the Java developer, the actual screen layout within the applet is completely controllable down to the pixel level. Graphics and Java are discussed briefly later in this chapter, and then in detail in Chapter 17, "Programming the User Interface." The remainder of this section presents the <APPLET> tag.

The <APPLET> Tag
The syntax for using the <APPLET> tag is the following:
<APPLET attributes>
applet_parameters
alternate_content
</APPLET>
The APPLET attributes are standard values that all applets accept and are a standard part of HTML. The applet_parameters are applet-specific parameters that are read by the applet at runtime. This is a handy way of passing arguments to an applet to allow the applet to be more generic.
<APPLET> Tag Attributes
ALT-Alternate text that can be displayed by text-only browsers.
ALIGN-The ALIGN attribute designates the alignment of the applet within the browser page.
CODE-(Required) The CODE attribute is used to indicate the .class file that loads the applet.
CODEBASE-The CODEBASE attribute is used to indicate the location of the .class file that loads the applet.
HEIGHT-(Required) The HEIGHT attribute is used to set the applet's bounding rectangle height.
HSPACE-The HSPACE attribute sets the amount of horizontal space to set off around the applet.
NAME-The NAME attribute sets the symbolic name of the applet.
VSPACE-The VSPACE attribute sets the amount of vertical space to set off around the applet.
WIDTH-(Required) The WIDTH attribute is used to set the applet's box width.

Passing Parameters to Java Applets

Parameters are an easy way to configure Java applets without actually changing the source file. In the previous applet example, the text drawn on the screen was drawn using the blue color. This was "hardwired" into the applet's code. However, just as easily, we could have passed a parameter to the applet specifying that it use the blue tag. Listing 7.3 shows the Example2.html file modified to do just this.


Listing 7.3. Passing parameters to the applet using HTML parameters.
<HTML>
<HEAD>
<TITLE>This is the LifeCycle applet!</TITLE>
</HEAD>
<BODY>
<H1>Prepare to be amazed!</H1>
<BR>
<APPLET CODE="LifeCycleApplet.class" WIDTH=600 HEIGHT=50>
<PARAM NAME=color VALUE="blue">
If you can see this, your browser does not support Java applets.
</APPLET>
</BODY>
</HTML>

The only question left to be answered is this: how does the Java applet determine the value of the parameters? (Excellent question!) The answer is that the applet has to call the getParameter() method supplied by the java.applet.Applet parent class. Calling getParameter("color") using the previous Java applet example would return a String value containing the text "blue". It is then left up to the applet to take advantage of this information and actually paint the text blue on the screen.

Here are three methods commonly used by applets:

Listing 12.9 in Chapter 12 shows a detailed example (with Java code) of using parameters to pass values to an applet using HTML parameters. For more detailed information on parameters and the <APPLET> tag, see Chapter 12.

Simple Graphics and GUI Techniques

This section presents an introduction to the graphical user interface capabilities provided in the Java Abstract Windowing Toolkit (AWT). The AWT is actually a package named java.awt included with the JDK. (For a complete documentation of the java.awt package, see Chapter 28.) Although there are many user interface classes contained in package java.awt, Table 7.1 lists the most commonly used classes with a brief description of each class.

Table 7.1. Commonly used user interface classes in package java.awt.
Class NameDescription
Button A standard pushbutton user interface component
Canvas A canvas that is used as a graphics drawing context
Checkbox A standard checkbox user interface component
CheckboxGroup A user interface component used to group checkboxes
CheckboxMenuItem A checkbox that is displayed as a menu item
Choice A menu component that displays the currently selected choice
Color A class used to encapsulate colors in Java
Component The base class of all user interface components
Container A base class for all container/grouping components
Dialog A standard dialog screen that can be either modal or nonmodal
FileDialog A standard file selection dialog that is OS-dependent
Font A class used to encapsulate fonts in Java
Frame A frame that can contain window objects
Graphics The base class used for all graphics and drawing operations
Image A class used to encapsulate images in Java
Label A standard label user interface component
List A standard list box user interface component
Menu A menu component that resides on a menubar
MenuBar The menubar that contains menus and menu items
MenuItem Menu selection items that trigger program events
Panel A user interface component used to surround other components
Scrollbar A standard scrollbar user interface component
TextArea A multiline text editing window
TextField A single-line text editing window
Window A window inside a frame that contains multiple objects

By examining this table, you can see that three primary classes of components exist within the AWT: drawing objects, containers, and user interface components. If you have ever done any type of GUI programming before, you are probably familiar with all of the components listed here.

Laying Out Components on the Screen

Before you dive into GUI programming with Java, there is one type of class contained in the AWT (not listed in Table 7.1) that may be new even to experienced programmers. This type of class is known as a layout manager. Layout managers allow components to be added onscreen without specifying exact coordinate locations for the components. This type of class makes working with onscreen components much easier. Because advanced "drag-and-drop" Java Developer's environments are not currently available, Java developers currently must either use layout managers or give specific screen coordinates to locate components onscreen. This will remain true in the future for developers coding on platforms that do not support advanced development environments. Here are some examples of layout managers:

Although the FlowLayout is the default layout manager used in the applet class, the following example (Listing 7.4) illustrates the use of the BorderLayout class. All this simple applet does at the current time is add a text box, a list, and a push button. Don't worry about the actual functionality now. This will be added when we discuss events in the next section.


Listing 7.4. The contents of EditList1.java.
import java.awt.TextField;
import java.awt.List;
import java.awt.Button;
import java.awt.BorderLayout;
import java.applet.Applet;

public class EditList1 extends java.applet.Applet
{
  TextField theText;
  List      theList;
  Button    theButton;


  public void init()
  {
    setLayout(new BorderLayout()); // sets the layout manager to be a
 BorderLayout

    theText = new TextField();
    theList = new List();
    theButton  = new Button("Add text to list!");

    add("North", theText);
    add("Center", theList);
    add("South", theButton);
  }
}

The EditList1 applet uses the BorderLayout Manager to automatically lay out a TextField, List, and Button. Figure 7.3 shows the EditList1 applet running within a Web browser using the Example3.html file.

Figure 7.3 : The EditList applet running within Netscape Navigator.

This is an exciting step, but this applet would be incomplete without some sort of functionality. We can use Java events to force some work to be done when the user clicks on a button, double-clicks the list, or edits the text. The next section will briefly discuss event handling. At the end of the section, the EditList1 applet will be modified so that when a user clicks the button, whatever text has been typed into the text field gets added to the list.

Handling Events

Event handling is one of the primary features of graphical user interface programming. It is so important that this type of interface is also commonly called an event-driven interface. If you stop to think about it, there are many events going on constantly within a standard user interface. Key presses, button clicks, and even voice activation can cause processing to occur on your computer. (In addition to common user events, the operating system itself commonly sends events to applications such as when a window is dragged over another window, or when the system itself is preparing to shut down.) To take advantage of this rich model, it is necessary to be able to "handle" or respond to these events in some way. Of course, Java provides this functionality, but it is up to the programmer to implement it. In the previous example, EditList1.java, the user can click on the button continuously, yet no text will ever be added to the list. This is because the default button-click event for the Button class does nothing except change the look of the button while the user is actually clicking it. It is up to the user to provide some type of functionality.

To trap an event sent from any user interface component, the programmer must define an action() method. By examining the documentation in Chapter 28 for the java.awt.Component class, you can see that this method is part of the Component class, which is the base class for all onscreen elements.

Note
There are two ways to trap events:
  • Override the applet's action() method and trap the events for all components within the applet. If this is done, the action() method's Event object will need to be examined so that the object that sent the event can be determined.
  • Create a new class for each component on the screen that needs to have its events handled. Then override the individual component's action methods.

Listing 7.5 (EditList2.java) uses the Applet class's action() method to trap the button-click event. When this event has been trapped, the contents of the edit control are added to the list box.


Listing 7.5. The contents of EditList2.java.
import java.awt.TextField;
import java.awt.List;
import java.awt.Button;
import java.awt.BorderLayout;
import java.applet.Applet;
import java.awt.Event;

public class EditList2 extends java.applet.Applet
{
  TextField theText;
  List      theList;
  Button    theButton;


  public void init()
  {
    setLayout(new BorderLayout()); // sets the layout manager to be a
 BorderLayout

    theText = new TextField();
    theList = new List();
    theButton  = new Button("Add text to list!");

    add("North", theText);
    add("Center", theList);
    add("South", theButton);
  }

  public boolean action(Event evt, Object arg)
  {
    if (evt.target instanceof Button)
      theList.addItem(theText.getText());

    return true;
  }
}

Running the Example4.html file within a Web browser will show that the event handling implemented above actually works. Figure 7.4 shows Example4.html running within the Netscape Navigator browser.

Figure 7.4 : The EditList2 applet running within Netscape Navigator.

Inter-Applet Communication

In the previous example, the button component was used to add items to the list component. All of these operations occurred inside a single applet. However, imagine a case where a button-click in one applet could update a database and trigger update messages to another applet running within the same Web page or even running on a remote computer. This type of communication is known as inter-applet communication. Since the early days of Java, this feature has been requested by developers wanting to push the envelope of Java's capabilities. This section briefly discusses several methods for communicating between applets, but you should note that these methods are browser-dependent and are subject to change.

Java Beans

Recently, a technology known as Java Beans has been introduced by JavaSoft. Java Beans is a component object model that will allow Java applets to be integrated with other applets and applications using multiple component architectures, including COM, OpenDoc, LiveConnect, and CORBA. This component model is supposed to compete heavily with Microsoft's Component Object Model (COM, which is the basis of ActiveX) and should be released in late 1996. Until then, however, developers who want to provide inter-applet communication must resort to other methods.

Possibilities of Inter-Applet Communication

There are several interesting possibilities that will be available when applets are truly enabled to communicate among themselves. Here are possible types of communication:

Using a technology such as Java Beans or ActiveX will also allow developers to "wrap" their applets with code that will expose an applet's methods and properties in some standardized way. Using the component model, the applet could potentially be dropped onto a Visual Basic form or used to communicate with applications written in other programming languages.

Some Inter-Applet Communication Methods

Once again, keep in mind that currently, the only way to implement this type of communication is to take advantage of specific browser features. The following examples focus on capabilities using the Netscape Navigator browser.

Note
Throughout this book, there has been and will be little mention of operating system-specific problems. This is because Java is truly a cross-platform development tool. However, it is interesting to note that there are many browser-specific tendencies. Perhaps those who say the Web browser is an operating system are somewhat correct. This is certainly true in the case of Java programming.

Using the AppletContext

Calling the getApplets() or getApplet() method is the easiest way to reach applets running within the same Web page. Although this feature appears to be relatively foolproof, there are some gotchas to watch out for. By examining the documentation on the getApplets() method in Chapter 27, you can see that this method returns an Enumeration containing all applets located within the current AppletContext. This works fine on browsers that treat a single Web page as an AppletContext; however, some browsers (including an earlier version of Sun's HotJava) break each applet up into a separate AppletContext. Be careful to really check out the browser your users will be using (in the intranet case) to make sure you really understand how this method actually works.

Using a Web Server

A somewhat more difficult, and less reliable, method of inter-applet communication is the use of socket-based communication between applets using the originating Web server. At the current time, any desired type of messaging service can be set up on the server, although it has been mentioned that Sun may discontinue this feature and limit communications to the server's HTTP port only.

Using JavaScript

The Netscape Navigator 3.0 browser implements a technology known as LiveConnect to allow an applet to expose its methods and data to the outside world. Using the scripting language known as JavaScript, the Web page developer can access and change an applet's internal data.

Netscape Navigator 3.0 will also allow the use of cookies. Cookies are basically text files that can contain messages. At the current time, only JavaScript can actually access cookies, but this feature could be useful to script together applets that were loaded at different times.

These features are truly browser-dependent. HTML files containing these features can only be displayed correctly using the Netscape Navigator 3.0 browser.

Using Static Variables

If both applets doing the communication share the same class, a common inter-applet communication mechanism is the use of static variables. Static variables can be thought of as global variables that apply to all instances of the class within an applet. However, the Netscape implementation of this feature allows static variables to be shared within an AppletContext's boundaries. This, then, is yet another method for "passing" data between applets within the same AppletContext.

Summary

The widespread use of Java applets is one of the most exciting software development technologies in recent memory. Applets offer the promise of truly platform-independent software that will allow developers to add interesting interactive content to their Web pages. Although the Java language itself is platform-independent, developers should be warned that vendor-specific additions such as Microsoft's ActiveX extensions could render Java applets unusable on non-Windows platforms. Before pursuing technologies such as this or inter-applet communication, be sure that the needs of users are clearly understood so that your applet development project will not be hindered in the future.

The next chapter discusses Java application development. At the current time, much of the development world has focused solely on Java applets, but Java applications are sure to see widespread growth in the near future as development tools become more powerful.