Friday 24 March 2017

Applet Basics, Applet Architecture & An Applet Skeleton - Java Tutorials

Applet Basics

All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt. Recall that AWT stands for the Abstract Window Toolkit. Since all applets run in a window, it is necessary to include support for that window. Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser or an applet viewer. The figures shown in this chapter were created with the standard applet viewer, called appletviewer, provided by the SDK. But you can use any applet viewer or browser you like.

Execution of an applet does not begin at main( ). Actually, few applets even have main( ) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism, which will be explained shortly. Output to your applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application.

Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag. This way, your code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting the applet viewer with your Java source code file specified as the target. Here is an example of such a comment:

  /*
  <applet code="MyApplet" width=200 height=60>
  </applet>
  */

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier, all of the applets shown in this book will contain the appropriate APPLET tag embedded in a comment.


The Applet Class

Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. (The AWT is described in detail in following chapters.)


The Methods Defined by Applet

void destroy( ):  Called by the browser just before an applet is terminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction.

AccessibleContext getAccessibleContext( ):   Returns the accessibilty context for the invoking object.

AppletContext getAppletContext( ):  Returns the context associated with the applet.

String getAppletInfo( ):  Returns a string that describes the applet.

AudioClip getAudioClip(URL url):  Returns an AudioClip object that encapsulates the audio clip found at the location specified by url.

AudioClip getAudioClip(URL url, String clipName):  Returns an AudioClip object that encapsulates the audio clip found at the location specified by url and having the name specified by clipName.

URL getCodeBase( ):  Returns the URL associated with the invoking applet.

URL getDocumentBase( ):  Returns the URL of the HTML document that invokes the applet.

Image getImage(URL url):  Returns an Image object that encapsulates the image found at the location specified by url.

Image getImage(URL url, String imageName):  Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName.

Locale getLocale( ):  Returns a Locale object that is used by various locale-sensitive classes and methods.

String getParameter(String paramName):  Returns the parameter associated with paramName. null is returned if the specified parameter is not found.

String[ ] [ ] getParameterInfo( ):  Returns a String table that describes the parameters recognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose.

void init( ):  Called when an applet begins execution. It is the first method called for any applet.

boolean isActive( ):  Returns true if the applet has been started. It returns false if the applet has been stopped.

static final AudioClip newAudioClip(URL url):  Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. This method is similar to getAudioClip( ) except that it is static and can be executed without the need for an Applet object. (Added by Java 2)

void play(URL url):  If an audio clip is found at the location specified by url, the clip is played.

void play(URL url, String clipName):  If an audio clip is found at the location specified by url with the name specified by clipName, the clip is played.

void resize(Dimension dim):  Resizes the applet according to the dimensions specified by dim. Dimension is a class stored inside java.awt. It contains two integer fields: width and height.

void resize(int width, int height):  Resizes the applet according to the dimensions specified by width
and height.

final void setStub(AppletStub stubObj):  Makes stubObj the stub for the applet. This method is used by the run-time system and is not usually called by your applet. A stub is a small piece of code that provides the linkage between your applet and the browser.

void showStatus(String str):  Displays str in the status window of the browser or applet viewer. If the
browser does not support a status window, then no action takes place.

void start( ):  Called by the browser when an applet should start (or resume) execution. It is automatically called after init( ) when an applet first begins.

void stop( ):  Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start( ).





Applet Architecture

An applet is a window-based program. As such, its architecture is different from the so-called normal, console-based programs shown in the first part of this book. If you are familiar with Windows programming, you will be right at home writing applets. If not, then there are a few key concepts you must understand.

First, applets are event driven. Although we won’t examine event handling until the following chapter, it is important to understand in a general way how the event-driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. Here is how the process works. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return control to the AWT. This is a crucial point. For the most part, your applet should not enter a “mode” of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the AWT run-time system. In those situations in which your applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its window), you must start an additional thread of execution. 

Second, the user initiates interaction with an applet—not the other way around. As you know, in a nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks a mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. As you will see in later chapters, applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated.

While the architecture of an applet is not as easy to understand as that of a console-based program, Java’s AWT makes it as simple as possible. If you have written programs for Windows, you know how intimidating that environment can be. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.




An Applet Skeleton

All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods—init( ), start( ), stop( ), and destroy( )—are defined by Applet. Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. These five methods can be assembled into the skeleton shown here:

  // An Applet skeleton.
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="AppletSkel" width=300 height=100>
  </applet>
  */

  public class AppletSkel extends Applet {
    // Called first.
    public void init() {
      // initialization
    }

    /* Called second, after init(). Also called whenever
       the applet is restarted. */
    public void start() {
      // start or resume execution
    }

    // Called when the applet is stopped.
    public void stop() {
      // suspends execution
    }

    /* Called when applet is terminated. This is the last
       method executed. */
    public void destroy() {
      // perform shutdown activities
    }

    // Called when an applet's window must be restored.
    public void paint(Graphics g) {
      // redisplay contents of window
    }
  }


Applet Initialization and Termination

It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the AWT calls the following methods, in this sequence:
  1. init( )
  2. start( )
  3. paint( )

When an applet is terminated, the following sequence of method calls takes place:
  1. stop( )
  2. destroy( )

Let’s look more closely at these methods.


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


start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen. 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 may be minimized and then restored. 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 parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.


stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. 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( ).


Overriding update( )

In some situations, your applet may need to override another method defined by the AWT, called update( ). This method is called when your applet has requested that a portion of its window be redrawn. The default version of update( ) first fills an applet with the default background color and then calls paint( ). If you fill the background using a different color in paint( ), the user will experience a flash of the default background each time update( ) is called—that is, whenever the window is repainted. One way to avoid this problem is to override the update( ) method so that it performs all necessary display activities. Then have paint( ) simply call update( ). Thus, for some applications, the applet skeleton will override paint( ) and update( ), as shown here:

  public void update(Graphics g) {
    // redisplay your window, here.
  }

  public void paint(Graphics g) {
    update(g);
  }

For the examples in this book, we will override update( ) only when needed.

2 comments: