Total Pageviews

ADD

Applet and Associated Class Summaries


Applet and Associated Class Summaries

Table 1-3 lists the classes and interfaces necessary for developing custom Applet objects in Java. The following sections describe each Class’ methods in more detail.
Table 1-3 Class and interface descriptions


Class/Interface
Description

AppletContext
Exposes services implemented by the applet browser for use by Applet objects. Conceptually, all active Applet objects have access to the same AppletContext.
Graphics
Encapsulates a drawing surface, and exposes tools for drawing graphics and rendering text on that drawing surface. A drawing surface may be a rectangle of the desktop, an in-memory image, or even a page in the printer.
Applet
Represents an embeddable Applet object.

AppletContext
Purpose
An interface which abstracts the browser to an Applet. Methods for testing and modifying the current state of the browser are provided as public members of this interface.
Syntax
interface AppletContext
Description
A running Applet gets its AppletContext using Applet.getAppletContext. Using this interface, the Applet can get and set some parameters of the browser’s current state. An Applet can get references to other Applets currently running in the browser, download images and audio clips, and load a new document into the browser through the AppletContext interface.
PackageName
java.applet
Imports
java.awt.Image, java.awt.Graphics, java.awt.image.ColorModel, java.net.URL, java.util.Enumeration
Constructors
None.
Parameters
None.
getApplet
Interface
AppletContext
Purpose
Used to facilitate inter-applet communications within a browser.
Syntax
public Applet getApplet( String strName );
Parameters
None.
String strName
This interface method implies the browser stores, with each loaded applet, a unique string to identify that applet. It passes to getApplet one of these unique applet identifiers to gain access to the associated Applet object.
Description
Multiple Applet objects can be simultaneously loaded and run by the same browser. Each applet runs within its own Thread. Use this method to access other applets running concurrently. It is completely up to a particular browser how to associate a particular string with an Applet object. For example, most commercial-grade World Wide Web browsers which are applet-aware use the NAME tag in the <APPLET> container tag to associate a name string with a particular applet, as in the HTML snippet below.
...
<APPLET CODE=MyApplet.class NAME="Chooser" WIDTH=100 HEIGHT=100>
<PARAM NAME="foo" VALUE="bar">
<PARAM NAME="blepharo" VALUE="spasm">
</APPLET>
Imports
None.
Returns
The Applet object associated with the unique String strName. If no applet is associated with strName, null is returned or if the applet browser does not provide facilities for inter-applet communications.
See Also
The getApplets method of the AppletContext interface
Example
The following example tries to find a set of other applets loaded by the browser. A report is written out to System.out indicating whether or not each applet could be found. The "applet-list" parameter contains a comma-separated list of applet names to look for. Only up to ten applets will be searched.
import java.applet.*;
 
public class AppletsSearchApplet extends Applet {
  String[ ] astrAppletNames = new String[11];
 
  public void init() {
    // Nothing displayed on browser, so shrink display surface
    resize( 0, 0 );
 
    /* Get the "applet-list" parameter, which contains a
     ** comma-separated list of applet names to search for.*/
    String strAppletListParam = getParameter( "applet-list" );
    if( null == strAppletListParam ) {
      System.out.println(
          "No \"applet-list\" parameter provided. );
    return;
    }
 
    /* Use the applet name list to initialize astrAppletNames.*/
    int iNameIndex = 0;
    int nStartIndex = 0;
    int nNextCommaIndex = 0;
 
    while( ( -1 != nNextCommaIndex ) && ( iNameIndex < 10 ) ){
      if( -1 == ( nNextCommaIndex =
          strAppletListParam.indexOf( ',', nStartIndex ) ) )
      astrAppletNames[ nNameIndex++ ] =
          strAppletListParam.substring( nStartIndex );
      else
        astrAppletNames[ nNameIndex++ ] =
            strAppletListParam.substring (
                nStartIndex, nNextCommaIndex );
 
      nStartIndex = nNextCommaIndex + 1;
    }
  }
 
  public void start() {
    // Look for each named applet in turn and report results.
    for( int iNameIndex = 0
        ; null != astrAppletNames[ iNameIndex ]
        ; iNameIndex++ ) {
      Applet applet = getAppletContext().getApplet(
          astrAppletNames[ iNameIndex ]);
      System.out.print( "Applet " +
          astrAppletNames[ iNameIndex ] + " " );
 
      if( null == applet )
        System.out.println( "not found!" );
      else
        System.out.println( "found!" );
    }
  }
 
  // stop() does not need to be implemented.
 
  public void destroy () {
    // Release the array of applet name strings.
    astrAppletNames = null;
  }
}

getApplets
Interface
AppletContext
Purpose
Used to facilitate inter-applet communications within a browser.
Syntax
public Enumeration getApplets();
Parameters
None.
Description
This method allows you to look up all applets currently running in the browser. The browser which implements this method will give you access to all Applet objects currently running in the browser.
Imports
None.
Returns
An Enumeration object is returned. Each element in the Enumeration is an Applet currently active in the browser. Note that an empty Enumeration, or a return of null, could be interpreted in two ways: Either getApplets() is not fully implemented by the browser, or no other applets are active in the browser.
No exact specification currently exists describing what getApplets should return in either of these situations.
See Also
The getApplet method of the AppletContext interface
Example
The following example uses getApplets and a custom interface, named Namable, to implement an applet-identification facility more complete than the AppletContext facility provided by getApplet and getApplets.
interface Namable {
  public String getName();
}
Here are the contents of FindNamableApplet.java:
public class FindNamableApplet extends Applet implements Namable {
  Hashtable hashAppletsByName;
  String strName;
  String strNameToFind;
 
  // getName simply returns the "name" parameter value.
  public String getName() {
    return strName;
  }
 
  // destroy releases references to object variables.
  public void destroy() {
    hashAppletsByName = null;
    strName = null;
    strNameToFind = null;
  }
 
  // init fills the applet hash table, and reads in parameters.
  public void init() {
    // Get the two expected parameters.
    if( null == ( strName = getParameter( "name" ) ) ) {
      System.out.println( "Name param missing!" );
      return;
    }
    if( null == ( strNameToFind = getParameter( "find" ) ) ) {
      System.out.println( "Find param missing!" );
      return;
    }
 
    // Add all Namable applets to hash table.
    Enumeration enumApplets = getAppletContext().getApplets();
    while ( enumApplets.hasMoreElements() ) {
      if( enumApplets.nextElement() instanceof Namable ) {
        Namable applet = (Namable)enumApplets.nextElement();
        hashAppletsByName.put( applet.getName(), applet );
      }
    }
  }
 
  // start() attempts to find strNameToFind applet, reports results
  public void start() {
    System.out.print( "Applet " + strNameToFind + " " );
 
    if( hashAppletsByName.containsKey( strNameToFind ) )
      System.out.println( "found." );
    else
      System.out.println( "not found!" );
  }
 
  // Unnecessary to implement stop().
}
getAudioClip
Interface
AppletContext
Purpose
Loads an audio file and readies it to be played by the browser.
Syntax
public AudioClip getAudioClip( URL url );
Parameters
URL url
Points to an audio data file to be loaded by the browser.
Description
Commercial-grade browsers, especially World Wide Web browsers, have built-in facilities for loading and playing audio files. Applets use the getAudioClip method to load audio files from any URL the browser can understand. Applets should use one of the overloaded Applet.getAudioClip methods to access AudioClips instead of AppletContext.getAudioClip. This method is rarely called by an Applet directly.
Imports
java.net.URL
Returns
The object returned by this function implements the AudioClip interface. If the URL is not understood by the browser, null will be returned or if the browser does not provide this functionality to applets.
Example
See the Applet.getAudioClip code example. Applet.getAudioClip is implemented as a simple pass-through to AppletContext.getAudioClip, similar to this code sample:
public Applet extends Panel {
  // Other Applet methods declared and implemented...
  // ...
 
  public AudioClip getAudioClip( URL url ) {
    // Use the AppletContext to load the audio clip
    return getAppletContext().getAudioClip();
  }
}

getImage
Interface
AppletContext
Purpose
To load an image from a URL and prepare it for rendering on a display surface.
Syntax
public Image getImage( URL url );
Parameters
URL url
Points to an image file to be loaded by the browser.
Description
Java applications must implement methods for reading and interpreting image files, and converting the image data into Image objects. Applets may have this functionality exposed to them by the browser through the AppletContext.getImage method. Browsers that can load and interpret various image formats, such as GIF, JPEG or TIFF, can provide that capability to applets. Applets simply provide a URL pointing to an image file in a recognized format. No methods are provided for an applet to query which image formats are supported by a browser. Therefore, it is usually a good idea to only try to load images in very common graphics formats, such as GIF or JPEG.
Imports
java.awt.Image
Returns
An Image object will be returned by this object, or null if this facility is not supported by the browser. The reaction of this method when the URL refers to an unsupported protocol, or when the image file format is unrecognized, is unspecified. Generally, it can be assumed that null will be returned if this capability it not provided by the browser.
See Also
The Image class
Example
The following sample applet loads and displays an image. A relative URL to the image to be loaded is passed to the applet as the "image" parameter. That parameter will be interpreted relative to the URL returned by Applet.getDocumentBase. An object of the MyImageObserver class is needed to receive an error message if there is a problem with loading or displaying the image.
import java.applet.*;
import java.awt.*;
 
class MyImageObserver implements ImageObserver {
  public boolean imageUpdate( Image image, int nInfoFlags,
      int nX, int nY, int nCx, int nCy ) {
    // If an error has been detected, report it.
    if( nInfoFlags & ImageObserver.ERROR )
    System.out.println( "Error with the image." );
    return true;
  }
}
 
public class ImageApplet extends Applet {
  Image image;
  MyImageObserver mio = new MyImageObserver;
 
  public void init() {
    // resize to some fixed size: large images will be clipped
    resize( 100, 100 );
 
    // Get the relative URL for the image
    String strRelativeURL = getParameter( "image" );
    if( null == strRelativeURL ) {
      System.out.println( "Image parameter missing." );
      return;
    }
    // Load the image.
    image = getAppletContext().getImage(
        getDocumentBase(), strRelativeURL );
    if( null == image )
      System.out.println( "Unable to load image." );
  }
 
  public void destroy() {
    // Get rid of reference to image and image observer.
    image = null;
    mio = null;
  }
 
  public void paint( Graphics g ) {
    // Paint image on display surface, if image exists
    if( null != image )
      g.drawImage( image, 0, 0, mio );
  }
}
showDocument
Interface
AppletContext
Purpose
Opens a new document in the browser. An overloaded version exists to specify the name of the target browser frame.
Syntax
public void showDocument( URL url ); public void showDocument( URL url, String target );
Parameters
URL url
Points to the document to be opened by the browser. If the protocol referred to by the URL is not recognized by the browser, this call will be ignored. If the document format implied by the URL’s file name is not recognized by the browser, this call will be ignored.
String target
You may specify a named browser-frame for the new document to appear in. Table 1-4 lists the valid values for this parameter
Table 1-4 Valid values of the String target parameter


Value
Meaning

"_self"
The same frame the Applet is embedded in.
"_parent"
The parent frame of the frame the Applet is embedded in.
"_top"
The top-level window this Applet appears in.
"_blank"
A new, top-level unnamed frame.
<other>
Any other name causes the browser to search for an extant frame with this name. If none exists, then a new top-level frame with this name is created.

Description
In the abstract, Applets are seen as being embedded in distributed "documents," such as World Wide Web pages. When implemented, this method allows the applet to force the browser to open a particular document pointed to by a URL. Like all other methods in this interface, a particular browser may not implement this method, in which case the browser will simply ignore a call to this method.
If the second overloaded version of this method is used, then the document will be opened in a browser frame with the same name as the target parameter.
Imports
java.net.URL
Returns
The Applet object associated with the unique String strName. If no applet is associated with strName, null is returned or if the applet browser does not provide facilities for inter-applet communications.
See Also
The getDocumentBase method of the Applet class
Example
This applet asks the browser to reload the current document whenever the Applet’s stop method is invoked. (Not generally a very nice thing to do.)
public class RestartingApplet extends Applet {
 
    public void stop() {
        AppletContext ac = getAppletContext();
        if(null != ac)
            ac.showDocument(getDocumentBase());
    }
 
}


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.

Graphics
Purpose
An AWT Component (such as an Applet) uses a Graphics object to draw on a display surface.
Syntax
public class Graphics
Description
A Graphics object is always associated with a "display surface." The display surface can be a rectangle of the on-screen desktop, an Image in memory, or potentially any rectangular area that can be drawn on. You use the Graphics class methods to render graphics and text on the display surface assoicated with the Graphics object. Figure 1-7 shows the class diagram for the Graphics class.
PackageName
java.awt
Imports
java.awt.*, java.image.ImageObserver
Constructors
None. You cannot create Graphics objects directly, but instead get them from other Java API methods. For example, Image.getGraphics returns a Graphics object, which uses the Image as its drawing surface.
Parameters
None.

Figure 1-7  Class diagram for the Graphics class
clearRect
ClassName
Graphics
Purpose
To erase the specified rectangle using the background color of the display surface associated with the Graphics object.
Syntax
public abstract void clearRect(int x, int y, int width, int height);
Parameters
int x, int y, int width, int height
These four parameters define the rectangle to be erased on the display surface.
Description
This method is used to erase a rectangle from the display surface. The associated display surface’s background color is used to fill the specified rectangle. This is a legacy method which was never removed from the alpha release of Java. Use of this method is not advised. Instead, use Graphics.fillRect, specifying the color you want to use to erase the rectangle. It is an unfortunate but true fact that the Java API does not specify an overloaded version of this method which takes a Rect object as a parameter. The origin and extent of the rectangle must be explicitly provided in the four parameters to this method.
Imports
None.
Returns
None.
See Also
The fillRect method of the Graphics class
Example
Use of this method is not advised, so an example is not provided.
clipRect
ClassName
Graphics
Purpose
To shrink the clipping rectangle of the Graphics object.
Syntax
public abstract void clipRect(int x, int y, int width, int height);
Parameters
int x, int y
These four parameters define the new clipping rectangle for the Graphics object.
int width
int height
Description
Use this method to modify the clipping rectangle of the Graphics object. The clipping rectangle restricts drawing on the drawing surface to within the rect. The resultant clipping rectangle is the intersection of the current clipping rect and the new one defined by the parameters passed to this method. That is, the clipping rectangle can never be made larger, only smaller. This is to prevent ill-behaved Components from enlarging their clipping rectangles to include the entire desktop and then drawing all over the desktop. The clipping rectangle is one of the internal state variables of all Graphics objects.
Imports
None.
Returns
None.
See Also
The create method of the Graphics class
Example
public class MyApplet extends Applet {
    public void paint(Graphics g) {
        // Get the current clipping rectangle
        Rect rectClip = g.getClipRect();
 
        // Try to enlarge the clipping rectangle. Since
        // you can’t enlarge clipping rectangles, resultant
        // clipping rect will be same size as original.
        g.clipRect(0, 0, 1000, 1000);
 
        // Shrink clipping rect by 10 on all sides. This
        // always returns intersection of old and new
        // rects.
        g.clipRect(rectClip.x+10, rectClip.y+10,
                rectClip.width-20, rectClip.height-20);
    }
}
copyArea
ClassName
Graphics
Purpose
Copies a rectangle of the display surface to a new location on the display surface.
Syntax
public abstract void copyArea(int x, int y, int width, int height, int dx, int dy);
Parameters
int x, int y, int width, int height
These four parameters define the source rectangle to copy from.
int dx
The origin of the target rectangle.
int dy
Description
Copies the pixels of a rectangle of the display surface to another rectangle of the same display surface. Note that the source rectangle may reside outside the clipping rectangle of the Graphics object.
Imports
None.
Returns
None.
See Also
The drawImage method of the Graphics class
Example
This example clears the target area by using the XOR drawing mode of the Graphics object. The target rectangle will be painted with the alternate XOR color after the operation is complete.
public void paint(Graphics g) {
    g.setXORMode(Color.white);
    Rect rectClip = g.getClipRect();
 
    // Copy clipping rectangle over itself, which causes
    // image to disappear, leaving only the alternate
    // color (Color.white, in this case).
    g.copyArea( clipRect.x, clipRect.y, clipRect.width,
            clipRect.height, clipRect.x, clipRect.y);
}
create
ClassName
Graphics
Purpose
Creates a copy of this Graphics object.
Syntax
public abstract Graphics create();
public abstract Graphics create(int x, int y, int width, int height );
Parameters
int x, int y, int width, int height
These parameters define the display surface of the returned Graphics object. The resultant clipping rectangle will be equal to the intersection of the original Graphics object’s clipping rectangle and the rectangle defined by these parameters.
Description
Creates a clone of the original Graphics object, attached to the same display surface and with the same internal state as the original Graphics object. The second overloaded version makes a new Graphics object attached to a specific rectangle of the original Graphics object’s display surface. As the example below illustrates, the create method is most useful when you want to shrink the clipping rectangle, but get the original, larger clipping rectangle back later.
Imports
None.
Returns
A Graphics object is returned which is a clone of the original. If the second overloaded version of this method is used, then the clipping rectangle of the resultant Graphics object will be equal to the intersection of the clipping rectangle of the original Graphics and the rectangle defined by the parameters to this method. Also, the origin of the resultant Graphics object will be at the point defined by the x and y parameters to this method.
See Also
The clipRect method of the Graphics class
Example
This example uses the create method to temporarily shrink the clipping rectangle of a Graphics object.
public void paint(Graphics g) {
    // Get clipping rect of original Graphics
    Rect rectClip = g.getClipRect();
 
    // create Graphics with smaller clipping rect.
    Graphics gTemp = g.create(rectClip.x+10, rectClip.y+10,
            rectClip.width-20, rectClip.height-20);
 
    // use smaller clip rect in temp Graphics
    ...
 
    // Clip rect of original Graphics is still preserved
    // (can’t do that with Graphics.clipRect!).
}
translate
ClassName
Graphics
Purpose
Moves the origin of the Graphics’ coordinate system.
Syntax
public abstract void translate(int x, int y);
Parameters
int x, int y
These two parameters define a point which is the new origin of the display surface. The parameters are offsets from the original Graphics object’s origin.
Description
Modifies the origin of the Graphics object. The origin is one of the internal state variables of Graphics objects.
Imports
None.
Returns
None.
Example
public void paint(Graphics g) {
    // Move the origin ten points to the right and down
    // before using the Graphics object...
    g.translate(10, 10);
 
    ...
}
draw3DRect
ClassName
Graphics
Purpose
Renders a raised or depressed rectangle on the Graphics’ display surface.
Syntax
public void draw3DRect(int x, int y, int width, int height, boolean raised);
Parameters
int x, int y, int width, int height
The dimensions of the rectangle to be rendered on the display surface
boolean raised
This parameter tells whether the beveling should imply a raised or depressed effect for the 3D rectangle.
Description
Renders a rectangle with beveled edges to create a 3D visual effect. The beveling can either imply a raised or depressed 3D rectangle. The shades of the beveling are choosen based on the current drawing color of the Graphics object. The darker shading will be roughly 70 percent as bright as the current drawing color. The lighter color will be roughly 140 percent as bright as the current drawing color. The beveling will be exactly one pixel wide.
Imports
None.
Returns
None.
See Also
The fill3DRect and drawRect methods of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a raised 3D rectangle, 20x20 in size
    g.draw3DRect(0, 0, 20, 20, true);
 
    // Draw a depressed 3D rectangle of same dimensions
    g.draw3DRect(10, 10, 20, 20, false);
}
drawArc
ClassName
Graphics
Purpose
Renders the arc of an oval’s wedge on the Graphics’ display surface.
Syntax
public abstract drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);
Parameters
int x, int y, int width, int height
The dimensions of the rectangle bounding an oval. The arc is taken as part of the circumference of this oval.
int startAngle
Measured in degrees, this defines the start of the arc. Zero degrees lies in the "3 o’clock" position.
int arcAngle
Measured in degrees, the distance of the arc around the oval. A positive value indicates a counter-clockwise direction around the oval. Negative indicates clockwise.
Description
Renders an arc of an oval on the display surface. The oval is defined by a bounding rectangle, and the arc is described by a starting and stopping angle in degrees.
Imports
None.
Returns
None.
See Also
The fillArc method of the Graphics class
Example
See the Nautilus example applet earlier in the chapter.

drawBytes
ClassName
Graphics
Purpose
Renders an array (or subarray) of bytes that are interpreted as ASCII character values, on the Graphics’ display surface.
Syntax
public abstract void drawBytes(byte data[ ], int offset, int length, int x, int y);
Parameters
byte data[ ]
The array of byte data of ASCII characters to render on the display surface.
int offset
The zero-based index of the first character to render.
int length
The number of ASCII characters to render.
int x
The horizontal offset from the origin to render the characters on the drawing surface.
int y
The vertical offset of the baseline where the text is to be rendered. This is measured from the current origin of the Graphics context.
Description
drawBytes renders text on the drawing surface taken from a subarray of an array of bytes. The bytes are interpreted as 8-bit ASCII character values. The current font and drawing color of the Graphics is used to render the text.
Imports
None.
Returns
None.
See Also
The drawString, drawChars, and setFont methods of the Graphics class
Example
public void paint(Graphics g) {
    // Initialize an array of bytes with ASCII character
    // values
    byte[ ] ab = new byte[10];
    ab[0] = ‘G’;
    ab[1] = ‘i’;
    ab[2] = ‘l’;
    ab[3] = ‘l’;
    ab[4] = ‘i’;
    ab[5] = ‘g’;
    ab[6] = ‘a’;
    ab[7] = ‘n’;
 
    // Render the ASCII characters to the drawing surface.
    // Baseline is 20 pixels below the origin.
    g.drawBytes(ab, 0, 8, 0, 20);
}
drawChars
ClassName
Graphics
Purpose
Renders an array of ASCII characters on the drawing surface. The array can be a subarray of a larger set of characters.
Syntax
public abstract void drawChars(char data[ ], int offset, int length, int x, int y);
Parameters
char data[ ]
The array of ASCII characters to render on the display surface.
int offset
The zero-based index of the first character to render.
int length
The number of ASCII characters to render.
int x
The horizontal offset from the origin to render the characters on the drawing surface.
int y
The vertical offset of the baseline where the text is to be rendered. This is measured from the current origin of the Graphics context.
Description
drawChars renders text on the drawing surface taken from a subarray of an array of characters. The array values are interpreted as ASCII character values. The Graphics object’s current font and drawing color are used to render the characters on the Graphics’ display surface.
Imports
None.
Returns
None.
See Also
The drawBytes, drawString, and setFont methods of the Graphics class
Example
public void paint(Graphics g) {
    // Initialize an array of chars with ASCII character
    // values
    char[ ] ac = new char[10];
    ac[0] = ‘S’;
    ac[1] = ‘k’;
    ac[2] = ‘i’;
    ac[3] = ‘p’;
    ac[4] = ‘p’;
    ac[5] = ‘e’;
    ac[6] = ‘r’;
 
    // Render the ASCII characters to the drawing surface.
    // Baseline is 20 pixels below the origin.
    g.drawChars(ac, 0, 8, 0, 20);
}
drawImage
ClassName
Graphics
Purpose
Renders an Image on the Graphics object’s display surface.
Syntax
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer);
public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer);
Parameters
Image img
The Image object to be displayed.
int x, int y
The coordinate of the upper-left corner of the image on the drawing surface
int width, int height
Using the second overloaded version of this method, you can specify the size of the target rectangle to copy the Image to. By using a different size than the original Image object, you can stretch/shrink the Image on the drawing surface.
ImageObserver observe
Notifies whether the image is complete or not. (See comments)
Description
The passed Image is copied to the drawing surface. The second overloaded version of this method allows you to stretch/shrink the Image on the drawing surface. The ImageObserver is notified about progress of copying the image to the drawing surface. This is useful especially if the Image object is created from a URL pointing to a .GIF or other graphics-format on the network. If, for example, the URL does not actually point to an image, or to an incomplete image file, the ImageObserver object is notified. This results in a little more overhead in coding, but the increase in coding results in more robust applets and applications. Note that all Components, including all Applets, automatically implement the ImageObserver interface. The default implementation of this interface causes the Component to be repainted whenever an update of the image is read in.
Imports
None.
Returns
None.
See Also
The getImage method of the Applet class; the getImage method of the Toolkit class; the ImageObserver interface; and the MediaTracker class
Example
This applet creates an image from a URL in its init implementation. In paint, that image is rendered twice on the applet’s display surface, once at the Image’s default size, and a second time stretched to fit the entire surface of the Applet.
public class MyApplet extends Applet {
    Image _img = null;
 
    // Create the Image from a URL in init.
    public void init() {
        _img = getImage(
            new URL("http://www.sample.com/sample.img"));
    }
 
    // In paint, render the image once stretched and once not
    // stretched.
    public void paint(Graphics g) {
        // Make sure _img is not null.
        if(null == _img)
            return;
 
        // Render the imge stretched, using this Applet
        // as the ImageObserver.
        g.drawImage(_img, 0, 0, size().width,
                size().height, this);
 
        // Render the image not stretched.
        // Again, using this Applet as the ImageObserver.
        g.drawImage(0, 0, this);
}

drawLine
ClassName
Graphics
Purpose
Renders a line between two points on the Graphics object’s display surface.
Syntax
public abstract void drawLine(int x1, int y1, int x2, int y2);
Parameters
int x1
One endpoint of the line segment to render on the drawing surface.
int y1
int x2
Other endpoint of the line segment to render on the drawing surface.
int y2
Description
Renders a line between the two points on the drawing surface. The current drawing color is used to render the line. Note that there is no way, using the Java API, to specify lines with a width greater than one pixel. To achieve wide lines, you must render multiple side-by-side lines on the display surface.
Imports
None.
Returns
None.
Example
The example uses the current drawing color to render a 5x5 grid on the Graphics’ clipping rectangle.
public void paint(Graphics g) {
    // Get the clipping rectangle and figure out grid
    // cell width and height from it.
    Rect rectClip = g.getClipRect();
    int cxCellWidth = rectClip.width / 5;
    int cyCellHeight = rectClip.height / 5;
 
    // Draw the grid.
    for( int ii=0 ; ii<=5 ; ii++ )
        for( int jj=0 ; jj<=5 ; jj++ ) {
            g.drawLine(ii*cxCellWidth, 0, ii*cxCellWidth,
                    size().height);
            g.drawLine(0, jj*cyCellHeight, size().width,
                    jj*cyCellHeight);
        }
}
drawOval
ClassName
Graphics
Purpose
Renders an oval defined by a bounding rectangle.
Syntax
public abstract void drawOval(int x, int y, int width, int height);
Parameters
int x, int y, int width, int height
These parameters define the bounding rectangle of the oval.
Description
Renders an oval on the display surface. The oval is defined as being bound by the four sides of the rectangle described by the input parameters to this method. The color of the resulting oval is the current drawing color of the Graphics object.
Imports
None.
Returns
None.
See Also
The fillOval method of the Graphics class
Example
See the Ovals example applet earlier in this chapter.
drawPolygon
ClassName
Graphics
Purpose
Renders a polygon on the Graphics object’s display surface.
Syntax
public abstract void drawPolygon(int xPoints[ ], int yPoints[ ], int nPoints);
public void drawPolygon(Polygon p);
Parameters
int xPoints[ ], int yPoints[ ]
These two arrays describe an ordered set of points which define the vertices of a polygon to be rendered on the drawing surface.
int nPoints
The number of vertices of the polygon to be rendered. This is also the number of elements in both the xPoints[ ] and yPoints[ ] arrays.
Polygon p
A Polygon object which describes the polygon to be rendered on the drawing surface
Description
Two overloaded versions of this method, both allow you to render a multisided polygon on the drawing surface. The logic of the rendering algorithm automatically closes the polygon by connecting the last point of the polygon to the first.
Imports
None.
Returns
None.
See Also
The fillPolygon method of the Graphics class; the Polygon class
Example
public void paint(Graphics g) {
    // Instantiate two arrays of coordinates with three
    // values each, indicating the vertices of a triangle.
    int[ ] acx = new int[3];
    int[ ] acy = new int[3];
 
    acx[0] = 0 ; acy[0] = 0 ;  // the point (0 , 0 )
    acx[1] = 10; acy[1] = 0 ;  // the point (10, 0 )
    acx[2] = 10; acy[2] = 10;  // the point (10, 10)
 
    // Draw the polygon represented by these three points
    g.drawPolygon(acx, acy, 3);
}
drawRect
ClassName
Graphics
Purpose
Renders a simple rectangle on the drawing surface.
Syntax
public abstract void drawRect(int x, int y, int width, int height);
Parameters
int x, int y, int width, int height
These parameters define the rectangle to be rendered on the drawing surface.
Description
Renders the rectangle defined by the four parameters on the Graphics’ display surface. Use drawRect(rect.x, rect.y, rect.width-1, rect.height-2) to render the outline of a particular Rect object. The rectangle is rendered using the Graphics’ current drawing color.
Imports
None.
Returns
None.
See Also
The fillRect method of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a 10x10 rectangle in the upper-left corner of
    // drawing surface.
    g.drawRect(0, 0, 10, 10);
}

drawRoundRect
ClassName
Graphics
Purpose
Renders a rectangle with rounded corners on the Graphics’ display surface.
Syntax
public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight);
Parameters
int x, int y, int width, int height
These parameters define the rectangle to be rendered on the drawing surface.
int arcWidth, int arcHeight
These two parameters define the width and height of the arcs that are each of the rounded corners. These number are both interpreted as the diameters of the arc at the four corners. So the width and height of the arc at each corner are 1/2 of the arcWidth and arcHeight parameters, respectively.
Description
Renders a rectangle with rounded corners on the drawing surface. Through the parameters to this method, both the width and height of the corner arcs can be defined. The outline of the rectangle is rendered using the current drawing color of the Graphics object.
Imports
None.
Returns
None.
See Also
The fillRoundRect method of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a rounded rect around the circumference of this
    // Component. Make the corners 5 pixels wide and tall
    // at the arc.
    Dimension d = size();
    drawRoundRect(0, 0, d.width-1, d.height-1, 10, 10);
}
drawString
ClassName
Graphics
Purpose
Renders a string of text on a drawing surface using the Graphics’ current font and drawing color.
Syntax
public abstract void drawString(String str, int x, int y);
Parameters
String str
String containing the text to be rendered on the drawing surface. The entire string will be rendered. To render a substring of a String object, use either the drawBytes or drawChars Graphics methods.
int x
The horizontal offset from the origin to render the String on the drawing surface.
int y
The vertical offset of the baseline where the text is to be rendered. This is measured from the current origin of the Graphics context.
Description
Draws the full String using the current font and drawing color. The left-most point of the baseline is indicated by the x and y parameters.
Imports
None.
Returns
None.
See Also
The drawBytes, drawChars, and setFont methods of the Graphics class
fill3DRect
ClassName
Graphics
Purpose
Renders a filled, raised, or depressed rectangle on the Graphics’ display surface.
Syntax
public void fill3DRect(int x, int y, int width, int height, boolean raised);
Parameters
int x, int y, int width, int height
These parameters define the dimensions of the rectangle to draw on the display surface.
boolean raised
This parameter tells whether the beveling should imply a raised or depressed effect for the 3D rectangle.
Description
Renders a rectangle with beveled edges to create a 3D visual effect. The beveling can either imply a raised or depressed 3D rectangle. The shades of the beveling are choosen based on the current drawing color of the Graphics object. The darker shading will be roughly 70 percent as bright as the current drawing color. The lighter color will be roughly 140 percent as bright as the current drawing color. The beveling will be exactly one pixel wide. The inside of the rectangle will be filled using the current drawing color of the Graphics object.
Imports
None.
Returns
None.
See Also
The draw3DRect and fillRect methods of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a filled raised 3D rectangle, 20x20 in size
    g.fill3DRect(0, 0, 20, 20, true);
    // Fill a depressed 3D rectangle of same dimensions
    g.fill3DRect(10, 10, 20, 20, false);
}
fillArc
ClassName
Graphics
Purpose
Renders a wedge of an oval on the Graphics’ display surface.
Syntax
public abstract fillArc(int x, int y, int width, int height, int startAngle, int arcAngle);
Parameters
int x,int width, int height
The dimensions of the rectangle bounding an oval. The arc is a wedge of int y this oval.
int startAngle
Measured in degrees, this defines the start of the arc. 0 degrees lies in the "3 o’clock" position.
int arcAngle
Measured in degrees, the distance of the arc around the oval. A positive value indicates a counter-clockwise direction around the oval. Negative value indicates a clockwise direction.
Description
Draws a wedge of an oval. The oval is defined by a bounding rectangle, and the wedge is described by a starting and stopping angle in degrees.
Imports
None.
Returns
None.
See Also
The drawArc method of the Graphics class
Example
See the Nautilus example Applet earlier in the chapter.


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions
fillOval
ClassName
Graphics
Purpose
Renders a filled oval defined by a bounding rectangle.
Syntax
public abstract void fillOval(int x, int y, int width, int height);
Parameters
int x, int y, int width
These parameters define the bounding rectangle of the oval to be rendered.
int height
Description
Renders a filled oval on the display surface. The oval is defined as being bound by the four sides of the rectangle described by the input parameters to this method. The color of the resulting oval is the current drawing color of the Graphics object.
Imports
None.
Returns
None.
See Also
The drawOval method of the Graphics class
Example
See the Ovals example Applet earlier in this chapter.
fillPolygon
ClassName
Graphics
Purpose
Renders a filled polygon on the Graphics object’s display surface.
Syntax
public abstract void fillPolygon(int xPoints[ ], int yPoints[ ], int nPoints); public void fillPolygon(Polygon p);
Parameters
int xPoints[ ], int nPoints, int yPoints[ ]
These two arrays describe an ordered set of points which define the vertices of a polygon to render on the drawing surface.
The number of vertices of the polygon to be rendered. This is also the number of elements in both the xPoints[ ] and yPoints[ ] arrays.
Polygon p
A Polygon object which describes the polygon to render on the drawing surface.
Description
Two overloaded versions of this method both allow you to render a multisided polygon on the drawing surface. The logic of the rendering algorithm automatically closes the polygon by connecting the last point of the polygon to the first. The odd-even filling algorithm is used to fill polygons. So for complex polygons, internal areas may or may not get filled. The general rule of thumb is that an area will be filled if a line segment drawn from outside the polygon to the area within the polygon crosses an odd number of the polygon’s line segments. If an even number is crossed, then the area will not be filled. For example, the center of a pentagram would not get filled, while each of the five arms of the pentagram would get filled.
Imports
None.
Returns
None.
See Also
The drawPolygon method of the Graphics class, the Polygon class
Example
public void paint(Graphics g) {
    // Instantiate two arrays of coordinates with three
    // values each, indicating the vertices of a triangle.
    int[ ] acx = new int[3];
    int[ ] acy = new int[3];
 
    acx[0] = 0 ; acy[0] = 0 ;  // the point (0 , 0 )
    acx[1] = 10; acy[1] = 0 ;  // the point (10, 0 )
    acx[2] = 10; acy[2] = 10;  // the point (10, 10)
 
    // Draw the polygon represented by these three points
    g.fillPolygon(acx, acy, 3);
}
fillRect
ClassName
Graphics
Purpose
Renders a simple filled rectangle on the drawing surface.
Syntax
public abstract void fillRect(int x, int y, int width, int height);
Parameters
int x, int y, int width, int height
These parameters define the rectangle to render on the drawing surface.
Description
Renders the filled rectangle described by the four parameters on the Graphics’ display surface. Use drawRect(rect.x, rect.y, rect.width-1, rect.height-2) to render a particular Rect object. The rectangle is rendered using the Graphics’ current drawing color.
Imports
None.
Returns
None.
See Also
The drawRect method of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a 10x10 rectangle in the upper-left corner of
    // drawing surface.
    g.fillRect(0, 0, 10, 10);
}
fillRoundRect
ClassName
Graphics
Purpose
Renders a filled rectangle with rounded corners on the Graphics’ display surface.
Syntax
public abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight);
Parameters
int x, int y, int width, int height
These parameters define the rectangle to render on the drawing surface.
int arcWidth, int arcHeight
These two parameters define the width and height of the arcs that are each of the rounded corners. These numbers are both interpreted as the diameters of the arc at the four corners. So the width and height of the arc at each corner is 1/2 of the arcWidth and arcHeight parameters, respectively.
Description
Renders a filled rectangle with rounded corners on the drawing surface. Through the parameters to this method, both the width and height of the corner arcs can be defined. The rectangle is rendered using the current drawing color of the Graphics object.
Imports
None.
Returns
None.
See Also
The drawRoundRect method of the Graphics class
Example
public void paint(Graphics g) {
    // Draw a rounded rect around the circumference of this
    // Component. Make the corners 5 pixels wide and tall
    // at the arc.
    Dimension d = size();
    g.fillRoundRect(0, 0, d.width-1, d.height-1, 10, 10);
}

getClipRect
ClassName
Graphics
Purpose
Returns a Rect whose members are set to the origin and dimensions of the current clipping rectangle for this Graphics object.
Syntax
public abstract Rectangle getClipRect();
Parameters
None.
Description
Allows you access to the clipping rectangle dimensions and placement, which is one of the internal state variables of the Graphics object. Drawing operations are only valid within the clipping rectangle. Graphics-intensive applet or applications are easily optimized in the paint method by performing only those operations valid within the clipping rectangle. For example, an application which renders lots of images to the drawing surface would see vast improvements in speed by only drawing those images which overlap with the clipping rectangle, since any drawing outside the clipping rectangle is ignored anyway.
Imports
None.
Returns
A Rectangle object which represents the position and size of the clipping rectangle relative to the origin of the Graphics object.
See Also
The clipRect and create methods of the Graphics class
Example
This paint method is responsible for rendering a 100x100 grid of Images on the drawing surface. The method is optimized by only rendering those Images which fall within the Graphics’ clipping rectangle.
// Assume a 100x100 array of Images has been initialized...
// each image is 10x10 pixels in size.
Image[ ][ ] _aaimg = new Image[100][100];
public void paint(Graphics g) {
    // get the clipping rectangle
    Rect rectClip = g.getClipRect();
 
    // only draw those images which overlap with the
    // clipping rectangle.
    int ii = rectClip.x/10 + (0 == rectClip.x%10 ? 0 : 1);
    int jj = rectClip.y/10 + (0 == rectClip.y%10 ? 0 : 1);
    int maxi = rectClip.width/10 +
            (0 == rectClip.width%10 ? 0 : 1);
    int maxj = rectClip.height/10 +
            (0 == rectClip.height%10 ? 0 : 1);
    for( ; ii<=maxi ; ii++ )
        for( ; jj<=maxj ; jj++ )
            // draw the ii-th, jj-th image, using
            // this Component as the ImageObserver.
            g.drawImage(_aaimg[ii][jj], ii*10, jj*10,
                    this);
}
getColor
ClassName
Graphics
Purpose
Gets the current rendering color of the Graphics object.
Syntax
public abstract Color getColor();
Parameters
None.
Description
Accesses the current foreground color of the graphics object, which is one of the internal state variables of the Graphics object. All graphical primitive and text rendering operations are done using the foreground color.
Imports
java.awt.Color
Returns
A Color object containing the relative RGB (Red/Green/Blue) values of the current foreground color of the Graphics object.
See Also
The setColor method of the Graphics class; the Color class
Example
This example uses both getColor and setColor to modify the Graphics’ current rendering color.
public void paint(Graphics g) {
 
    // Get current drawing color.
    Color c = g.getColor();
 
    // Modify current color by switching red and blue
    // color values.
    g.setColor(new Color(c.getBlue(), c.getGreen,
            c.getRed());
    
    // Do drawing with the new color.
    ...
}
getFont
ClassName
Graphics
Purpose
Gets the current font of the Graphics object.
Syntax
public abstract Font getFont();
Parameters
None.
Description
Accesses the current font of the Graphics object The current font is one of the internal state variables defining the current state of a Graphics object. All text rendering operations are done using the currentFont.
Imports
java.awt.Font
Returns
A Font object describing the current font in use by the Graphics object.
See Also
The setFont method of the Graphics class; the Font class
Example
This example uses getFont and setFont to make the current font for rendering text boldface.
public void paint(Graphics g) {
    // Get the current Font.
    Fonr f = g.getFont();
 
    // change the Font by making a boldface version of it.
    g.setFont(new Font(f.getName(),
        f.getStyle() | Font.BOLD, f.getSize());
 
    // Do something with the new font...
    ...
}
getFontMetrics
ClassName
Graphics
Purpose
Returns a FontMetrics object for the Font and the display surface associated with this Graphics object.
Syntax
public abstract FontMetrics getFontMetrics();
public abstract FontMetrics getFontMetrics(Font f);
Parameters
Font f
A specific Font to get a FontMetrics for. The resultant FontMetrics represents the metrics of text rendered on the display surface associated with this Graphics object using Font f.
Description
The same font can actually render differently on different display surfaces, especially if those display surfaces represent very dissimilar graphical devices. A FontMetrics object describes how the font will render on a particular Graphics object’s display surface. The first overloaded version of this method will generate a FontMetrics describing how the Graphics object’s current font, one of the variables of the Graphic’s internal state, will display on the drawing surface. The other overloaded version allows you to pass in a Font object.
Returns
A FontMetrics object describing how the specified font, defined by a Font object, will be displayed on the Graphic’s drawing surface.
See Also
The getFont and setFont methods of the Graphics class
Example
public void paint(Graphics g) {
    // Get the FontMetrics for the current Font on
    // g’s display surface.
    FontMetrics fm = g.getFontMetrics();
 
    // Display width of the string "Ginger" to System.out.
    System.out.println("Width of ‘Ginger’ is " +
        fm.stringWidth("Ginger"));
}


scale
ClassName
Graphics
Purpose
Changes the scale of the X and Y axes of this Graphics object’s coordinate system.
Syntax
public abstract void scale(float xScale, float yScale);
Parameters
float xScale
The new ratio of physical device units of the display surface to logical units of the Graphics object in the horizontal direction.
float yScale
The new ratio of physical device units of the display surface to logical units of the Graphics object in the vertical direction.
Description
This method allows you to modify the ratio of physical device units to logical device units in both the horizontal and vertical directions. The scale of the Graphics object is one of the internal state variables that can affect the appearance of rendered geometric primitives, text, and images on the display surface.
The physical device units of a display surface are an atomic measure of the smallest addressable surface element. For example, the physical device units of the on-screen desktop are pixels. Pixels are also the physical device units of Image objects in memory.
Changing the scale of a Graphics object attached to the on-screen desktop to, say, two would mean that every pixel on the display surface was represented by two logical units of the Graphics object. In that case, a reference to the point (10,10) in a Graphics method would actually map to a physical point 5 pixels to the right and 5 pixels below the origin on the screen.
Different graphical devices have different physical device units. The physical device units of a laser printer probably would be much smaller than those of a dot-matrix printer.
Imports
None.
Returns
None.
setColor
ClassName
Graphics
Purpose
Modifies the current rendering color of this Graphics object.
Syntax
public abstract void setColor(Color c);
Parameters
Color c
A Color object containing the RGB (Red/Green/Blue) values of the color to use for the new foreground color of the Graphics object.
Description
Changes the current foreground color used by the Graphics object when rendering geometric primitives or text on the display surface. The current foreground color is one of the internal state variables that defines the current state of a Graphics object.
Imports
None.
Returns
None.
See Also
The getColor method of the Graphics class; the Color class
Example
See the example for the getColor method of the Graphics class.
setFont
ClassName
Graphics
Purpose
Modifies the font used for rendering text by this Graphics object.
Syntax
public abstract void setFont(Font f);
Parameters
Font f
A Font object describing the font to use when rendering text on the display surface using any of the Graphics class’ text rendering methods.
Description
Changes the current font used by the Graphics object when rendering text on the display surface. The current font is one of the internal state variables that defines the current state of a Graphics object.
Imports
None.
Returns
None.
See Also
The getFont method of the Graphics class; the Font class
Example
See the example for the getFont method of the Graphics class. 
setPaintMode
ClassName
Graphics
Purpose
Sets the painting mode of this Graphics object to "overwrite", as opposed to XOR mode.
Syntax
public abstract void setPaintMode();
Parameters
None.
Description
Changes the current painting mode used by the Graphics object when rendering geometric primitives or text on the display surface to "overwrite". When using this mode, all rendering overwrites the current display surface contents using the current foreground color. The current painting mode is one of the internal state variables that defines the internal state of a Graphics object.
Imports
None.
Returns
None.
See Also
The setXORmode method for the Graphics class
Example
This example uses both the overwrite and XOR painting modes in the same custom paint method implementation.
public void paint(Graphics g) {
    // Make sure painting mode is "overwrite".
    g.setPaintingMode();
 
    // draw a couple of boxes.
    g.fillRect(0, 0, size().width, size().height);
    g.drawRect(0, 0, size().width-1, size().height-1);
 
    // put Graphics into XOR mode, using white as the
    // alternate color.
    g.setXORMode( Color.white );
 
    // draw some more boxes. Overlapping areas will
    // be shown as white.
    g.fillrect(10, 10, size().width-20, size().height-20);
    g.drawRoundRect(10, 10, size().width-20,
        size().height-20, 10, 10);
}
setXORMode
ClassName
Graphics
Purpose
Changes the Graphics object’s painting mode to XOR mode, as opposed to overwrite mode.
Syntax
public abstract void setXORMode(Color c);
Parameters
Color c
A Color object containing the RGB (Red/Green/Blue) values of the color to use for the alternate to the foreground.
Description
Changes the current painting mode used by the Graphics object when rendering geometric primitives or text on the display surface to "XOR" mode. In XOR mode, the color value of a pixel, after a rendering operation, can be determined by this formula:
outColor(x, y) = inColor(x, y) ⊗ drawingColor ⊗ alternateColor

where the ⊗ symbol denotes the bitwise XOR operation.
Imports
None.
Returns
None.
See Also
The setPaintingMode method of the Graphics class
Example
See the Ovals Applet example earlier in this chapter.
Applet
Purpose
An embeddable interactive Component, suitable for embedding in World Wide Web pages using special HTML tags.
Syntax
public class Applet extends Panel
Description
A Java Applet is an interactive Component specially designed for use across the World Wide Web. The Applet class defines methods for controlling the lifetime of an Applet object, for which your applets provide custom implementations. Each applet running in an applet-aware browser has its own Thread, which uses the Applet methods init, start, stop and destroy to control the applet’s lifetime. The Applet communicates with the browser through AppletContext and AppletStub objects. Figure 1-8 illustrates the inheritance relationship of the Applet class.

Figure 1-8  Class diagram of the Applet class
PackageName
java.applet
Imports
java.awt.*
Constructors
None.
Parameters
None.
isActive
ClassName
Applet
Purpose
Indicates whether or not the Applet has been started.
Syntax
public boolean isActive();
Parameters
None.
Description
Just before the Applet’s start method is called, the Applet is marked as "active". At that point, all calls to this method return true. Before that time and just before destroy is called, the Applet is marked as not active.
Imports
None.
Returns
True is returned if this method is called at any time from just before the Applet’s start method is called to just before the Applet’s destroy method is called.
Example
Check to see if Applet "Professor" is active.
...
Applet appletProf =
        getAppletContext().getApplet("Professor");
if(null != appletProf)
    if(appletProf.isActive())
        System.out.println("Professor is active!");
...
getDocumentBase
ClassName
Applet
Purpose
Gets the URL for the document this Applet is embedded in.
Syntax
public URL getDocumentBase();
Parameters
None.
Description
The URL for the document this Applet is embedded in is returned. This method is a shallow wrapper around AppletStub.getDocumentBase, so if the AppletStub is not implemented then, a call to this method will cause a NullPointerException to be thrown.
Imports
java.net.URL
Returns
The URL pointing to the document this Applet is embedded in.
See Also
The getCodeBase method of the Applet class.
Example
...
System.out.println("Doc base is: " + getDocumentBase());
...
getCodeBase
ClassName
Applet
Purpose
Gets the URL for this Applet’s .CLASS file.
Syntax
public URL getCodeBase();
Parameters
None.
Description
The URL for the this Applet’s .CLASS file is returned. This method is a shallow wrapper around AppletStub.getCodeBase, so if the AppletStub is not implemented, then a call to this method will cause a NullPointerException to be thrown.
Imports
java.awt.URL
Returns
The URL pointing to this Applet’s .CLASS file.
See Also
The getDocumentBase method of the Applet class
Example
...
System.out.println("Code base is: " + getCodeBase());
...
getParameter
ClassName
Applet
Purpose
Gets the string value of a particular Applet parameter.
Syntax
public String getParameter(String name);
Parameters
String name
Name of the parameter to retrieve. This is the value of the "name" tag within the HTML <PARAM> field which defines the Applet.
Description
This method returns one of the parameters to this Applet. Parameters are declared between the <APPLET>..</APPLET> delimiters in HTML files. The <PARAM> tag has two possible fields: "name" and "value". By indicating one of the valid names for this Applet, the corresponding "value" field string will be returned.
Imports
None.
Returns
The String associated with the parameter whose "name" field value is the name parameter. If no such parameter exists, then null is returned.
See Also
The getParameters method of the Applet class
Example
...
// Retrieve each of the Applet’s parameters and print
// all their values.
String[ ][ ] aastrParams = getParameters();
for( int ii=0 ; ii<aastrParams.length ; ii++ )
    System.out.println(aastrParams[ii],
        getParameter(aastrParams[ii]));
...
getAppletContext
ClassName
Applet
Purpose
Retrieves the AppletConext for this Applet.
Syntax
public AppletContext getAppletContext();
Parameters
None.
Description
The AppletContext represents the browser this Applet is being displayed on. To retrieve a reference to an Applet’s AppletContext, use this method.
Imports
java.applet.AppletContext
Returns
A reference to this Applet’s AppletContext is returned. Note that if the Applet is not instantiated within a proper browser, then this method will return null. That is, if you have an application which simply creates an Applet instance, then that Applet’s AppletContext will be null.
See Also
The getAppletStub method of the Applet class
Example
This example uses the AppletContext to get an array of all the applets running within the browser.
...
Enumeration e = getAppletContext().getApplets();
// do something with each Applet in the Enumeration...
...
showStatus
ClassName
Applet
Purpose
Displays a message on the browser’s status bar.
Syntax
public void showStatus(String msg);
Parameters
String msg
Message to be displayed on the browser’s status bar.
Description
Browsers generally have a status bar below the main display window. Use this method to place a message within that status bar. This method is a shallow wrapper around AppletContext.showStatus. If the Applet is not created within the context of a browser which implements AppletContext, then a call to this method will throw a NullPointerException.
Imports
None.
Returns
None.
See Also
The showStatus method of the AppletContext class
Example
...
public void start() {
    // Show message indicating the Applet was started...
    showStatus("Applet started!");
...
}
...

play
ClassName
Applet
Purpose
Downloads and plays an AudioClip from an audio data file.
Syntax
public void play(URL url); public void play(URL url, String str);
Parameters
URL url
URL or base of a relative URL to the audio data file for the AudioClip you want to play.
String str
Relative URL to the URL you want to play.
Description
This method is a simple shorthand for getting an AudioClip and playing it. Use of this method saves about three lines of explicit coding.
Imports
java.applet.AudioClip, java.net.URL
Returns
None.
See Also
The getAudioClip method of the Applet class; the AppletContext class; the AudioClip interface
Example
This example reproduces the code of the ThemeMusicApplet, provided earlier in this chapter.
import java.Applet.*;
 
public class ThemeMusicApplet extends Applet {
  AudioClip audclipTheme;
 
  public void init() {
    // load the audio clip.
    audclipTheme = getAudioClip( getDocumentBase(),
        "images/theme.au" );
 
    // shrink display surface...never used.
    resize( 0, 0 );
  }
 
  public void start() {
    // start the audio loop.
    audclipTheme.loop();
  }
 
  public void stop() {
    // halt the audio loop.
    audclipTheme.stop();
  }
 
  public void destroy() {
    // release the audio clip from memory.
    audclipTheme = null;
  }
}
init()
ClassName
Applet
Purpose
Called by the Applet’s Thread to allow it to initialize itself.
Syntax
public void init();
Parameters
None.
Description
The init() method is one of the four methods which define an Applet’s action during its lifetime. In your custom applet, implement this method to allocate any resources you will need for your applet to run. The init() method is called only once, and always before this first invocation of the applet’s start() method.
Imports
None.
Returns
None.
See Also
The start(), stop(), and destroy() methods of the Applet class
Example
See the project for this chapter, which makes extensive use of the Applet’s init(), start(), stop(), and destroy() methods.
start()
ClassName
Applet
Purpose
Called by the Applet’s Thread to start it running.
Syntax
public void start();
Parameters
None.
Description
The start() method is one of the four methods which define an Applet’s action during its lifetime. In your custom applet, implement this method to actually perform the applet’s behavior. The start() method is potentially called several times during the lifetime of the applet. Each call to start() is matched by exactly one subsequent call to stop(), sometime in the future. A typical operation performed in the start() method is kick-starting the applet’s background Threads.
Imports
None.
Returns
None.
See Also
The init(), stop(), and destroy() methods of the Applet class
Example
See the project for this chapter, which makes extensive use of the Applet’s init(), start(), stop(), and destroy() methods.
stop()
ClassName
Applet
Purpose
Called by the Applet’s Thread to stop it running.
Syntax
public void stop();
Parameters
None.
Description
The stop() method is one of the four methods which define an Applet’s action during its lifetime. In your custom applet, implement this method to gracefully shut down the applet. The stop() method is potentially called several times during the lifetime of the applet. Each call to stop() is matched by exactly one prior call to start(). Stop any background Threads from processing before returning from your custom implementation of this method.
Imports
None.
Returns
None.
See Also
The init(), start(), and destroy() methods of the Applet class
Example
See the project for this chapter, which makes extensive use of the Applet’s init(), start(), stop(), and destroy() methods.
destroy()
ClassName
Applet
Purpose
Called by the Applet’s Thread to allow it to perform final clean-up.
Syntax
public void destroy();
Parameters
None.
Description
The destroy() method is one of the four methods which define an applet’s action during its lifetime. In your custom applet, implement this method to deallocate any resources allocated during the applet’s lifetime. The destroy() method is called exactly once, just before the Applet object is destroyed.
Imports
None.
Returns
None.
See Also
The init(), start(), and stop() methods of the Applet class
Example
See the project for this chapter, which makes extensive use of the Applet’s init(), start(), stop(), and destroy() methods.

The Applet and Graphics Project: The Game of Life

Project Overview

The Applet and Graphics class project demonstrates a non-trivial applet, suitable for embedding in a World Wide Web page and viewing with an applet-enabled Web browser. This project illustrates animation using double-buffered screen updating to minimize "flicker", and background Thread processing to create successive animation images. As with several of the Applet code samples provided in this chapter, the Life applet uses custom implementations of the essential Applet methods init(), start(), stop(), and destroy() to manage resources and processing during the lifetime of the Life applet object.
"The Game of Life" is a simple example of artificial life on the computer, introduced by Conway in 1970. The "game" is played on a grid. Each cell on the grid is designated as either "alive" or "not-alive" (i.e., dead), termed the cell’s "state". At each turn of the game, the computer determines the state of each cell in the grid based on the state of the cell and its adjacent cells in the previous turn. These are the rules for determining a cell’s state:
  An alive cell remains alive in the next turn if there are exactly two or three adjacent alive cells. This is termed the "loneliness rule".
  A dead cell becomes alive in the next turn if there are exactly three adjacent alive cells. This is termed the "reproduction rule".
  All other cells, whether alive or dead, will be dead the next turn.
It is fun and interesting to watch this program build cell colonies through turn-by-turn application of the above rules. Huge clusters of cells can die out from over-population, while small clusters of five or six cells can grow into mammoth cell structures. Figures 1-9, 1-10, and 1-11 present screenshots from three successive turns, or "generations," of a particular run through the Game of Life using the Life applet built in this project.

Figure 1-9  Turn or generation of the Game of Life

Figure 1-10  Turn or generation of the Game of Life

Figure 1-11  Turn or generation of the Game of Life
Note that in the Life.java code, an underscore character "_" is prepended to all class member variables to distinguish them from function names, local variables, etc. This is to improve the readability of the code.

Assembling the Project

1.  Begin the file named Life.java by declaring the Life Applet with its necessary member variables and object instances:
import java.applet.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.Color;
import java.awt.MediaTracker;
import java.net.URL;
 
public class Life extends Applet implements Runnable,
    ImageObserver {
 
  /* State variables. */
  boolean[ ][ ] _a2dfGameGrid;    // Stores current generation
  int _nGeneration;               // keeps track of turn #
  boolean _fGameGridDisplayed;    // Has current grid been displayed?
  Thread _threadNextGen;          // Calcs next generation.
 
  int _nxCells;                   // Game grid width.
  int _nyCells;                   // Game grid height.
 
  int _nxCellPixels;              // phys. width of each cell.
  int _nyCellPixels;              // phys. height of each cell.
  int _nxCellOrigin;              // phys. origin of cell 0,0.
  int _nyCellOrigin;              // phys. origin of cell 0,0.
 
  int _nxPixels;                  // Applet width in pixels.
  int _nyPixels;                  // Applet height in pixels.
 
  Image _imageAlive;               // Image to use for "alive"
                                        cells.
  Image _imageDead;                // Image to use for "not-alive"
                                        cells.
 
  Image _image2ndSurface;          // Image for 2ble buffering.
  Graphics _gc2ndSurface;          // Graphics for 2ble buffering.
 
  MediaTracker _medtrack;          // To track alive and dead images.
 
  /* Constants */
  static final int DEF_XCELLS = 100;
  static final int DEF_YCELLS = 100;
2.  The Life class’ overriding implementation of imageUpdate prevents Life Applet objects from repainting during construction of Images downloaded by the Applet. Life will later explicitly handle repainting with a background Thread.
  /* ********
   * imageUpdate() is called when the Alive and Dead cell
   * images are being loaded. An ImageObserver-implementing
   * class is required to draw images, which this applet class
   * implements with this method.
   ******** */
  public synchronized boolean imageUpdate( Image img,
      int nFlags, int x, int y, int width, int height ) {
    return true;
  }
3.  Life’s init implementation reads in the applet parameters, allocates and fills in the initial generation game grid, resizes the display area of the applet, and loads the "alive" and "not-alive" images.
public void init() {
    /*
     ** Retrieve the Game Grid dimensions
     ** ( _nxCells x _nyCells ). If not given,
     ** use default Game Grid size.
     */
    try {
     _nxCells = Integer.parseInt(
          getParameter( "xCells" ) );
     _nyCells = Integer.parseInt(
          getParameter( "yCells" ) );
      } catch (Exception e) {
     _nxCells = DEF_XCELLS;
     _nyCells = DEF_YCELLS;
    }
 
    /*
     ** Retrieve the physical display size
     ** ( _nxPixels x _nyPixels ). If not given,
     ** use the Game Grid size ( _nxCells x _nyCells ).
     */
    try {
     _nxPixels = Integer.parseInt(
          getParameter( "xPixels" ) );
     _nyPixels = Integer.parseInt(
          getParameter( "yPixels" ) );
   } catch (Exception e) {
     _nxPixels = _nxCells;
     _nyPixels = _nyCells;
   }
 
   /*
    ** Calculate the physical cell size.
    */
   _nxCellPixels = _nxPixels / _nxCells;
   _nyCellPixels = _nyPixels / _nyCells;
   _nxCellOrigin = ( _nxPixels / 2 ) -
          ( ( _nxCellPixels * _nxCells ) / 2 );
   _nyCellOrigin = ( _nyPixels / 2 ) -
          ( ( _nyCellPixels * _nyCells ) / 2 );
 
   /*
    ** Create the initial Game Grid, and fill it
    ** with the initial pattern of cells.
    ** Note that setGameGrid automatically repaints
    ** the applet.
    */
   _fGameGridDisplayed = false;
   _a2dfGameGrid = placeInitialPatternToGrid(
          createNewGameGrid( _nxCells, _nyCells ),
         _nxCells, _nyCells );
   _nGeneration = 0;
 
   /*
    ** Create the 2nd surface for double-buffered
    ** drawing.
    */
   _image2ndSurface = createImage( _nxPixels, _nyPixels );
   _gc2ndSurface = _image2ndSurface.getGraphics();
   _gc2ndSurface.setColor( Color.black );
   _gc2ndSurface.setPaintMode();
 
   /*
    ** Create the media tracker, and start it loading
    ** the alive and dead images.
    */
    _medtrack = new MediaTracker( this );
    _medtrack.addImage( getAliveImage(), 0 );
    if( null != getDeadImage() )
      _medtrack.addImage( getDeadImage(), 1 );
    return;
  }
4.  Life’s start method creates the Calc Thread, using this object’s run() method to do the successive game grid generation.
public synchronized void start() {
    /*
     ** Create the Calc thread and start it running.
     */
    _threadNextGen = new Thread( this );
    _threadNextGen.start();
    return;
  }
5.  The Calc Thread, created and started in Life’s start() method implementation, is made to halt in stop(). The run() method (below) is written so that the Calc Thread will stop running when the _threadNextGen member variable is null. Note that both the start() and stop() methods are synchronized to prevent simultaneous execution by more than one Thread.
public synchronized void stop() {
    /*
     ** Remove references to the Calc thread, which will
     ** cause it to stop processing very soon. The
     ** resume wakes up the (potentially) suspended
     ** Calc thread.
     */
    Thread threadTempRef = _threadNextGen;
    _threadNextGen = null;
    threadTempRef.resume();
 
    return;
  }
6.  Life’s Calc Thread, which calculates successive generations of the game grid, executes the run() method. The Calc Thread drops out of the continuous loop when _threadNextGen is set to null in Life.stop(). Once a new game grid is created, Life’s setGameGrid() method is called to update the display.
public void run() {
    boolean[ ][ ] a2dfNewGrid = null;
    int[ ][ ] a2dnSums = new int[ _nxCells ][ _nyCells ];
    int nI;
    int nJ;
 
    /*
     ** Make sure the alive and dead images have
     ** been loaded before really doing anything
     ** in this thread.
     */
    try {
       _medtrack.waitForID( 0 ); // the alive image
       if( null != getDeadImage() )
         _medtrack.waitForID( 1 ); // the dead image.
  } catch (Exception e) {}
 
   /*
    ** This continuous loop generates iterative
    ** generations of Life.
    */
   while( null != _threadNextGen ) {
     /*
      ** Allocate a new game grid only if current
      ** game grid is using the last one we
      ** allocated, or if we never allocated one
      ** before here.
      */
     if( ( null == a2dfNewGrid ) ||
          ( _a2dfGameGrid == a2dfNewGrid ) )
        a2dfNewGrid = createNewGameGrid( _nxCells,
            _nyCells );
 
     /*
      ** Clear out the Sums grid for this iteration.
      */
     for( nI=0 ; nI<_nxCells ; nI++ )
       for( nJ=0 ; nJ<_nyCells ; nJ++ )
         a2dnSums[ nI ][ nJ ] = 0;
 
     /*
      ** To calc next generation: run through current
      ** generation: for each "alive" cell, do this:
      **  Add 1 to the Sums grid of each adjacent cell.
      **  Add 9 to the Sums grid of this cell.
      ** When we're done, only cells with Sum of
      ** 3 (dead w/ 3 adjacent), 11 (alive w/
      ** 2 adjacent), or 12 (alive w/ 3 adjacent)
      ** will be alive in the new grid.
      */
     for( nI=0 ; nI<_nxCells ; nI++ )
        for( nJ=0 ; nJ<_nyCells ; nJ++ )
          if( _a2dfGameGrid[ nI ][ nJ ] ) {
            for( int nII=-1 ; nII<2 ; nII++ )
              if( ( 0 <= nI + nII ) &&
                  ( _nxCells > nI + nII ) )
                for( int nJJ=-1 ; nJJ<2 ; nJJ++ )
                  if( ( 0 <= nJ + nJJ ) &&
                      ( _nyCells > nJ + nJJ ) )
                    a2dnSums[ nI+nII ]
                        [ nJ+nJJ ] += 1;
                a2dnSums[ nI ][ nJ ] += 8;
          }
 
          for( nI=0 ; nI<_nxCells ; nI++ )
            for( nJ=0 ; nJ<_nyCells ; nJ++ )
              switch( a2dnSums[ nI ][ nJ ] ) {
                case 3:
                case 11:
                case 12:
                  a2dfNewGrid[ nI ][ nJ ] = true;
                  break;
                default:
                  a2dfNewGrid[ nI ][ nJ ] = false;
              }
          /*
           ** Make sure the current game grid
           ** has been displayed before updating
           ** the game grid with the next generation.
           */
          while( ( ! setGameGrid( a2dfNewGrid ) ) &&
              ( null != _threadNextGen ) )
            try {
              _threadNextGen.suspend(); // this thread
            } catch (Exception e) {}
     }
 
     return;
  }
7.  Paint() is called by the Java system asynchronously whenever the Life Applet must be updated on screen. This can be in response to an explicit call to Life.repaint() (done in setGameGrid()), or in response to a windowing event such as the Life applet being scrolled off and then back on screen. This implementation of paint uses the current game grid to place multiple copies of the "alive" and "not-alive" images to an in-memory Image. When the in-memory Image has been updated, it is copied to the screen. The update() method is overriden to call paint() without doing anything else.
public synchronized void paint(Graphics g) {
    int nI;
    int nJ;
 
    /*
     ** Display the grid on the applet surface. This
     ** involves just running through all the cells
     ** and placing the corrosponding image on the
     ** display surface,
     */
    _gc2ndSurface.fillRect( 0, 0, _nxPixels, _nyPixels );
 
    for( nI=0 ; nI<_nxCells ; nI++ )
      for( nJ=0 ; nJ<_nyCells ; nJ++ )
        if( _a2dfGameGrid[ nI ][ nJ ] )
          _gc2ndSurface.drawImage( getAliveImage(),
              ( nI * _nxCellPixels ) + _nxCellOrigin,
                  ( nJ * _nyCellPixels ) + _nyCellOrigin,
               this );
        else if ( null != getDeadImage() )
          _gc2ndSurface.drawImage( getDeadImage(),
              ( nI * _nxCellPixels ) + _nxCellOrigin,
                  ( nJ * _nyCellPixels ) + _nyCellOrigin,
              this );
    g.drawImage( _image2ndSurface, 0, 0, this );
 
    _fGameGridDisplayed = true;
    /*
     ** Use resume() to release the (potentially)
     ** suspended Calc thread.
     */
    _threadNextGen.resume();
 
    return;
  }
 
public void update(Graphics g) {
    paint(g);
  }
8.  setGameGrid() is called by the Calc Thread after it has completed calculating the next generation. This is synchronized so paint(), start(), or stop() cannot be entered while the current game grid is being updated.
private synchronized boolean setGameGrid(
    if( ! _fGameGridDisplayed )
        return false;
 
    try {
      System.arraycopy( a2dfGrid, 0, _a2dfGameGrid,
          0, _nxCells );
    } catch(Exception e) {
    _a2dfGameGrid = a2dfGrid;
    }
 
    _fGameGridDisplayed = false;
    _nGeneration++;
    repaint();
    return true;
  }
9.  Life implements several utility methods to make the code in the previous steps more readable.
  /* ********
   * createNewGameGrid( x, y ) allocates and returns a reference
   * for a 2d array of booleans.
   ******** */
  private boolean[ ][ ] createNewGameGrid( int xCells, int yCells ) {
    boolean[ ][ ] a2dfNewGrid = new boolean[ xCells ][ yCells ];
    return a2dfNewGrid;
  }
 
  /* ********
   * placeInitialPatternToGrid( boolean[ ][ ] ) will read in
   * the initial cell pattern from the three applet
   * parameters "xStartPatternCells", "yStartPatternCells",
   * and "strStartPattern". The start pattern will be
   * placed centered on the 2d array passed in.
   ******** */
  private boolean[ ][ ] placeInitialPatternToGrid(
      boolean[ ][ ] a2dfGrid, int nxGridCells,
      int nyGridCells )
  {
    /*
     ** Get the dimensions of the starting pattern.
     ** xStartPatternCells and yStartPatternCells
     ** are not optional parameters.
     */
    int nxStartCells = Integer.parseInt(
        getParameter( "xStartPatternCells" ) );
    int nyStartCells = Integer.parseInt(
        getParameter( "yStartPatternCells" ) );
 
    /*
     ** Calculate the X and Y cell offsets to
     ** begin placing the initial pattern on
     ** the grid.
     */
    int nxPatternOffsetCells = ( nxGridCells / 2 ) -
        ( nxStartCells / 2 );
    int nyPatternOffsetCells = ( nyGridCells / 2 ) -
        ( nyStartCells / 2 );
 
    /*
     ** Retrieve the start pattern descriptive string.
     */
    String strStartPattern =
        getParameter( "strStartPattern" );
 
    /*
     ** For each cell in the starting pattern, update
     ** the corresponding grid cell.
     */
    int iPatternString = 0;
    for( int nI=0 ; nI<nxStartCells ; nI++ )
      for( int nJ=0 ; nJ<nyStartCells ; nJ++ ) {
        int iNext0 = strStartPattern.indexOf(
            '0', iPatternString );
        int iNext1 = strStartPattern.indexOf(
            '1', iPatternString );
 
        if( ( iNext0 < iNext1 ) &&
            ( iNext0 != -1 ) )
          iPatternString = iNext0 + 1;
        else if( iNext1 != -1 )
          iPatternString = iNext1 + 1;
        else {
          nI = nxStartCells;
          nJ = nyStartCells;
          continue;
      }
 
      a2dfGrid[ nI+nxPatternOffsetCells ]
          [ nJ+nyPatternOffsetCells ] =
              ( strStartPattern.charAt(
                  iPatternString - 1 ) ==
                       '1' );
    }
 
    return a2dfGrid;
  }
 
  /* ********
   * getAliveImage()
   * getDeadImage()
   * These methods are responsible for identifying and loading
   * the "alive" and "not-alive" cell images. The alive image
   * is the only one required. The "urlAliveImage" parameter
   * holds a relative URL to the "alive" cell image, and the
   * "urlDeadImage" parameter holds a relative URL to the
   * "not-alive" cell image.
   ******** */
  private Image getAliveImage() {
    if( null == _imageAlive ) {
        URL urlAliveImage = null;
      try {
        urlAliveImage = new URL( getDocumentBase(),
            getParameter( "urlAliveImage" ) );
      } catch (Exception e) {}
      _imageAlive = getImage( urlAliveImage );
      }
 
  return _imageAlive;
}
 
  private Image getDeadImage() {
    if( null == _imageDead ) {
      if( null == getParameter( "urlDeadImage" ) )
        return null;
 
      URL urlDeadImage = null;
      try {
        urlDeadImage = new URL( getDocumentBase(),
            getParameter( "urlAliveDead" ) );
      } catch (Exception e) {}
      _imageDead = getImage( urlDeadImage );
    }
 
    return _imageDead;
  }
};
10.  Enter the following HTML code into a file named EXAMPLE1.HTML in the same directory as Life.java:
<HTML>
<HEAD>
<TITLE>Life Applet Example</TITLE>
</HEAD>
<BODY>
<H1>Life Applet Example</H1>
Below is the Game of Life applet.
<HR>
<CENTER>
<APPLET CODE="Life.class" WIDTH=300 HEIGHT=300>
<PARAM NAME="xPixels" VALUE="300">
<PARAM NAME="yPixels" VALUE="300">
<PARAM NAME="xCells" VALUE="30">
<PARAM NAME="yCells" VALUE="30">
<PARAM NAME="urlAliveImage" VALUE="alive.gif">
<PARAM NAME="xStartPatternCells" VALUE="10">
<PARAM NAME="yStartPatternCells" VALUE="10">
<PARAM NAME="strStartPattern"
        VALUE="1111111100
               1100000011
               1100000011
               1111111100
               1111111100
               1100000011
               1100000011
               1100000011
               1111111100
               1111111100">
</APPLET>
</CENTER>
<HR>
Here's <A HREF="Life.java">the source</A>
</BODY>
</HTML>

How It Works

Table 1-5 lists the applet parameters, both required and optional, used by the Life applet.
Table 1-5 Life applet parameter descriptions


Parameter
Required
Description

xCells, yCells
Yes
The number of columns and rows, respectively, of the grid of cells to be displayed by the Life applet.
xPixels, yPixels
Yes
The physical size of the applet’s display surface in pixels.
urlAliveImage
Yes
A URL pointing to an image the applet is to use to represent alive cells.
urlDeadImage
No
A URL pointing to an image the applet is to use to represent dead cells. If this parameter is not provided, the applet displays nothing in dead cells.
xStartPattern Cells and yStartPatternCells
Yes
The number of columns and rows, respectively, of the initial pattern of cells described by the strStartPattern parameter.
strStartPattern
Yes
A string of "1" and "0" characters describing the initial states of the grid of cells. This string should have exactly (xStartPatternCells * yStartPatternCells) "1" or "0" characters in it. All other characters in the string are ignored. The string is interpreted as a left-to-right, top-to-bottom list of cell states. The initial pattern is centered on the Life grid automatically.

Three important techniques are used by the Game of Life applet:
  Double-buffering to ensure smooth visual transition between successively displayed frames.
  Overriding Component.update() to avoid "flicker".
  Background processing to generate successive animation frames.

Double-Buffered Rendering

Life’s paint method has the responsibility of displaying a grid of MxN cells. One way this could be accomplished is by simply rendering each cell on the applet’s drawing surface is a nested for loop:
public void paint(Graphics g) {
    for( nI=0 ; nI<M ; nI++ ) {
        for( nJ=0 ; nJ<N ; nJ++ ) {
            displayCell( nI, nJ, g );
        }
    }
}
The big problem with this method of display is that, especially for large M and N, the user will see each individual row of the display surface get updated. For less jerky animation, the successive frames should simply "pop" onto the screen, fully rendered. That’s what "double-buffered rendering" does: It allows you to update the display surface all at once, instead of little-by-little.
In double-buffered rendering, an Image object is created in memory with the exact same dimensions as the applet’s display surface. All rendering is done to a Graphics object attached to that in-memory Image object. When all rendering is completed, the Image object is copied to the display surface all at once. This has the practical effect of having the on-screen display updated instantaneously, instead of little-by-little.
In the Life applet, an in-memory Image, _image2ndSurface, is created during init with the same dimensions as the applet’s display surface. A Graphics object, _gc2ndSurface, is created attached to the in-memory Image, like this:
public void init() {
    // ...
    _image2ndSurface = createImage( _nxPixels, _nyPixels );
    _gc2ndSurface = _image2ndSurface.createGraphics();
    // ...
}
In paint(), the individual Life generations (each generation is an animation frame) are rendered to the _gc2ndSurface Graphics object. When the rendering is complete, the entire _image2ndSurface is copied to the applet’s display surface.

Overriding Update()

As hinted earlier in this chapter, the Java runtime system will automatically erase an applet’s drawing surface before paint() is called. For nonanimation sequences, this might not be a bad thing to do, but for fast screen updating it can prove to be quite annoying to look at. Between each two frames appears a brief "flicker" when the background is erased. The code for the default implementation of Component.update, which is responsible for the "flicker" problem, looks like this:
public void update(Graphics g) {
    // ...
    g.fillRect(0, 0, width, height);
    // ...
    paint(g);
}
To reduce this flicker problem, the Life applet implements its own update method to override the default implementation it inherits from Component. The overriding implementation does not call fillRect, so the background is not erased. The custom implementation looks like this:
public void update(Graphics g) {
    paint(g);
}

Animation Techniques

Two different animation techniques are the opposite poles of a continuum of implementations for animation in Java:
  Timesliced animation
  Computed frame animation
The simplest animation technique using Java timeslice animation, involves creating a background Thread to "timeslice", or sleep for some quanta of time before waking up and repainting the drawing surface. This is the "simplest" method because it involves the least amount of coding. To implement this animation technique, you need:
  An ordered Vector or array of Image objects, each one a frame to display.
  A "current Image object" variable, which keeps track of which frame is currently being displayed.
  A background Thread object which wakes up periodically, advances the "current Image object" indicator to the next frame, and forces the applet to repaint itself.
The JDK includes a generic Animator applet which uses the timeslicing technique to perform animation. Through its parameters, you can customize the Animator applet to display any number of frames, in any order, and even sequence sound with each frame.
The drawback of this animation technique is that it requires all frames of the animation sequence to have already been rendered onto Image objects in memory. For applets or applications which must compute and render each frame separately, such as the Life applet, the timeslicing technique is inadequate. Life uses the "computed frame" technique of animation.
The computed frame technique works by using a background Thread to compute sufficient information to render each frame "on the fly". In a continuous loop, the animation Thread computes a frame, and tells the drawing surface to display it, computes a frame, displays it, etc. In this technique, the time between the display of each frame is not necessarily constant, as in timesliced animation. Instead, the time between successive frames is dependent on how long it takes to compute and render each frame.
It is in Life’s run method that each successive generation of the Life game is computed. The actual computation involves keeping an accumulated sum for each cell in the target generation grid. For each generation, run adds values to this accumulator using these two rules:
  One is added to the accumulator of each cell adjacent to an "alive" cell.
  Nine is added to the accumulator of each "alive" cell.
Based on the rules of the Game of Life presented above, only cells with an accumulated value of 2, 3, or 12 will be alive in the next generation.
The most important aspect of the run method, however, is how it is sychronized with the rendering. The synchronization is necessary to prevent a newly computed Life generation, stored in a 2D grid of boolean values, from overwriting the grid currently being rendered by the paint method.
It is conceivable under the computed frame technique for there to be a backlog of unrendered frames. This will occur if the time it takes the background Thread to compute new frames is less than the time it takes to actually render frames. In such a case, the background Thread will generate more frames than can be rendered in the same amount of time. Without proper synchronization, this could lead to frames being skipped, or other problems.
The Life applet ensures these problems won’t occur by synchronizing access to the current generation grid. The background Thread will automatically suspend itself if it attempts to overwrite the current generation grid before it has been rendered on the drawing surface. A more sophisticated animation applet would utilize a synchronized storage device for storing any backlog of unrendered grids.