Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Applets And Graphics

java



+ Font mai mare | - Font mai mic



Applets And Graphics

Packaging interactive content in small, easily distributed objects was a design feature that had high priority to the developers of Java. To meet this design goal, they created the Applet class, along with several objects and interfaces designed to simplify image and audio processing.

An Applet is a custom interface component object, similar in concept to a Windows custom control, or an X-Windows widget. Applet-aware applications (or 'applet browsers') can load and construct Applet objects from URLs pointing to .CLASS files anywhere on a network, including the Internet, the largest network of them all. The Java Developer Kit's (JDK) HotJava World Wide Web browser is an example of an applet-aware application. Using it, you can access interactive Applets from anywhere on the Internet, or Applets developed on the local file system. Security features of the Java language ensure distributed applets cannot damage or compromise the security of a local system.



Using the graphical capabilities of Java, applets are visually exciting multimedia elements. Through objects of the class java.awt, Graphics applets can create graphical on-screen content. The Graphics class is included in this chapter because of the need for applets to display exciting visuals.

Because of all these features, applets have become the preferred method for distributing interactive content on the World Wide Web. A library of reusable, extensible Applets is one of the cornerstones of an Internet content creator's toolkit.

The project for this chapter is an Applet implementation of Conway's Game of Life. This project illustrates the use of 'double-buffered' animation, the preferred method of graphics animation in Java.

Applets

Figure 1-1 illustrates the Applet class hierarchy. Most ancestors of Applet in this hierarchy are Abstract Windows Toolkit (AWT) classes. Through them, the Applet class inherits windowing capabilities. Specifically, the Applets display, surface drawing, and mouse and keyboard event handling functionalities are gained through these ancestors. AWT's windowing capabilities are covered in Chapter 9. All examples and discussions in this chapter stop short of utilizing AWT methods other than those that provide applets with their graphical capabilities. But keep in mind the rich set of facilities the AWT classes have when designing your own custom Applet classes.


Figure 1-1  The Applet class hierarchy

Applet objects are created and controlled by a container application called an applet browser. The applet browser (see Figure 1-2) arranges applet objects visually on the screen and dedicates a rectangle of screen space for the applet to display itself. Most applet browsers can manage more than a single Applet object at a time, and actually provide an interface for the Applet instances to communicate with each other.


Figure 1-2  Example of an applet browser (JDK's AppletViewer) with a Java Applet running

The Essential Applet Methods

The actions of a custom Applet object are ruled by four essential methods: Applet.init, Applet.start, Applet.stop, and Applet.destroy. The browser itself invokes these methods at specific points during the applet's lifetime. The java.applet.Applet class declares these methods and provides default implementations for them. The default implementations do nothing. Custom applets override one or more of these methods to perform specific tasks during the lifetime of the custom Applet object. Table 1-1 lists these four methods, details when each is called by the browser, and shows what a custom applet's overriding implementation should do.

Table 1-1 Descriptions of the essential applet methods


Method

Description


init

Called once and only once when the applet is first loaded. Custom implementations allocate resources that will be required throughout the lifetime of the Applet object.

destroy

Called once and only once just before the Applet object is to be destroyed. Custom implementations release allocated resources, especially Native resources, which were loaded during init or during the lifetime of the Applet object.

start

Called each time the applet is displayed or brought into the user's view on-screen. Custom implementations begin active processing or create processing threads.

stop

Called each time the applet is removed from the user's view. Custom implementations end all active processing. Background processing threads should either be destroyed in stop, or put to sleep and destroyed in the destroy method.

The proper place to allocate objects or load data required by the applet throughout its lifetime is init. This method is called only once during the lifetime of the applet, right after the object is created by the browser. Most custom Applets allocate resources required throughout the lifetime of the Applet object in this method. Another very common operation performed during init is to resize the applet's on-screen display surface using the inherited method Component.resize. Some browsers display applets correctly only if the applet calls resize() in init(). The Component class is described in Chapter 2.

Listing 1-1 defines an applet that plays an audio clip in a continuous loop. This applet could be used to play 'theme music' while a particular Web page was being viewed. Notice that the essential methods init, start, stop, and destroy are given overriding implementations to manage what the applet does in the browser.

Listing 1-1 Example applet

import java.Applet.*;

public class ThemeMusicApplet extends Applet

public void start()

public void stop()

public void destroy()

The browser invokes the ThemeMusicApplet's start method when it is time to present information to the user, and ThemeMusicApplet.start begins playing the audio clip loaded in init. You can see why it is necessary for init to be invoked before any call to start: The audio clip must be loaded before it is played. init is always called before the first invocation of start.

When the applet drops from view, for example because it is scrolled off the screen in the browser or the user opens a different document in the browser, the applet's stop method is called. This is the proper time for a custom Applet to cease any processing. In our example, the continuous audio clip started in ThemeMusicApplet.start is halted in stop.

There are two more important technical notes about start and stop:

.  Every call to start has a matching subsequent call to stop.

.  The start/stop sequence may be repeated more than one time for the same custom Applet object, for example if the applet is scrolled from the user's view and then scrolled back. When it is scrolled from the user's view, stop will be invoked. When it is scrolled back, start will be invoked for the second time.

When the applet is finally and definitely to be unloaded from memory, destroy() is invoked. This is the appropriate time to delete any resources loaded during init(). The above example applet removes its reference to the AudioClip in destroy. The call to destroy is guaranteed to occur after the last call to stop. Note that while any resources allocated by an applet will automatically be cleaned up by Java's garbage collection facilities, it is more efficient to remove references to any allocated objects in destroy. Also note that resources allocated by 'native' methods will not be cleaned up by the garbage collection facilities. Native resources must be explicitly released in destroy. (Native methods are platform-specific, dynamically loadable libraries accessible from within Java code. For the most part, Applet classes do not use native methods because of the severe security constraints placed on Applet objects. Refer to Appendix C for more information about creating and using native methods in Java.) Figure 1-3 illustrates the sequence of calls to init, start, stop, and destroy by an applet browser.


Figure 1-3  Sequence of init, start, stop, and destroy calls for an Applet

Applet Parameters

Similar to Java applications, applets can receive and process parameters. Applications receive parameters in the argv[ ] argument to the main method. The elements of argv[ ] are the command line arguments to the application. Analogous to argv[ ], applet parameters are accessed within the applet code by the Applet.getParameter method.

The use of parameters makes applets extensible. ThemeMusicApplet.init has the theme music relative URL 'audio/theme.au' hardcoded into the init method. This listing uses a replacement for init, which makes the ThemeMusicApplet applet play whatever audio file is passed in its 'Theme' parameter:

public void init()

Conceptually, the browser maintains an internal listing of all the parameters passed to an embedded Applet object. The getParameter method accesses this internal list and retrieves the values specified for a uniquely named parameter. Our new listing uses the getParameter method to look up the value for the parameter named 'Theme'. If no such parameter was passed, getParameter would return null.

There is a method defined so that Applet objects can publish a list of valid parameter names, valid values, and a description of each. By overriding the Applet.getParameterInfo method, an Applet class can make this information public to any other object. The default implementation of getParameterInfo simply returns null, but an overriding implementation should return a String[n][3] 2-dimensional array where n is the number of unique parameters understood by members of the Applet class. Each row of three strings in this array should be of the format:


There is no strict requirement on the format of any one of these strings. Each one should be suitable for textual display so that someone can read it. For example, the 'valid value range' string could be '0-5', meaning the parameters should be an integer between 0 and 5. Listing 1-2 defines a small Applet class called AppletNames that displays, on System.out, a listing of all other active Applets currently being managed by the browser and a listing of each Applet object's parameter information retrieved using each Applet object's getParameterInfo method. This Applet class uses its AppletContext to access other active Applet instances. A detailed description of the AppleContext interface and methods follows this discussion of Applet parameters.

Listing 1-2 Example using the AppletNames class

import java.applet.*;
import java.util.*;

public class AppletNames extends Applet

public void start() catch( Exception e )
}
}

System.out.println( 'End of applet list.' );
}

Different types of browsers use different methods for passing parameters to applets. For example, applet-aware World Wide Web browsers generally use the HTML <APPLET> container tag to refer to applet code and parameters. Between the <APPLET> and </APPLET> container tags, zero or more <PARAM> tags can appear. These tags have the form <PARAM name=[param-name] value=[param-val]>. No matter how parameters are passed into a particular browser, a loaded applet always uses getParameter to retrieve parameter values.

Listing 1-3 is part of an HTML document with the ThemeMusicApplet embedded in it. The <APPLET> container refers to the ThemeMusicApplet's .CLASS file URL. The <PARAM> tag indicates which audio file to use ('audio/GilligansIsland.au').

Listing 1-3 HTML document



<H1>My Theme Music Home Page!</H1>
<P>Just sit right back and you should hear my theme music if
you wait for a moment for audio downloading

<APPLET SRC='ThemeMusicApplet' width=0 height=0>
<PARAM name='Theme' value='audio/GilligansIsland.au'>
</APPLET>


Communications Between the Applet and the Browser

Applets obtain information about the state of the browser, what other Applet objects are currently active, what is the current document opened by the browser, and so on, through the java.applet.AppletContext interface. The browser is abstracted by an object implementing this interface.

The browser also exposes some functionalities that an applet can use through this interface. For example, the loading of image and audio files into Java objects is handled transparently through the AppletContext interface. The two overloaded versions of Applet.getAudioClip are actually shallow wrappers around AppletContext.getAudioClip. The full AppletContext interface is detailed in the API descriptions for this chapter.

Between the AppletContext and the Applet is an AppletStub object. Its purpose is to provide a pathway for the exchange of applet-specific data between the AppletContext and the Applet. For example, the parameters for a specific Applet object are accessed by the Applet through AppletStub.getParameter. Applet.getParameter is actually a shallow wrapper around this method. In turn, AppletStub methods are translated into native or custom AppletContext method calls (the implementation of the pathway of data exchange between the AppletStub and AppletContext is left completely up to the browser developers). An Applet's AppletStub is tightly wrapped by the java.applet.Applet implementation. So much so, that all AppletStub functionalities are exposed as wrapper methods in the java.applet.Applet class. Therefore, a custom applet should never need to use its AppletStub directly. Figure 1-4 illustrates the pathways of data exchange between the Applet, the browser (abstracted by the AppletContext interface), and the AppletStub (the Applet's representative to the browser).


Figure 1-4  Pathways of data exchange between the Applet, AppletContext, and AppletStub objects

Using Threads in Applets

Much the same as applications, applets can create Threads to carry on background processing. A typical use of this would be an animation applet. To perform animation, the applet creates a new Thread and starts it running in start. The animation Thread acts as a timer. Every so often, it wakes and draws a new frame in the animation sequence, then suspends itself until the next frame is to be drawn. In the applet's stop method, the animation thread is shutdown. Two versions of this simple animation technique are described in greater detail in the section on the Graphics class and methods. The important point here is that Threads generally are made to begin background processing in an applet's start implementation and either suspended or destroyed in the applet's stop implementation.

You might assume that Threads created by an applet would be automatically halted by the browser when the applet is destroyed, so you wouldn't really need to suspend or destroy a Thread object explicitly in stop. Instead, you could just leave it to Java's garbage collection facilities to destroy your Thread when the Applet object is destroyed. Many browsers, however, do not properly halt secondary applet threads, even after the applet has been destroyed, so the thread continues to execute after the applet has been destroyed. This is a result of applets relying on the Java garbage collection facility to destroy their threads. To ensure your custom applets behave as you want them to, including ceasing when you want them to cease, suspend any secondary threads in Applet.stop, and drop references to them in destroy. As Listing 1-4 shows, the ClockTickApplet demonstrates using this technique in a multithreaded applet.

Listing 1-4 The ClockTickApplet sourcer

import java.applet.*;

public class ClockTickApplet extends Applet implements Runnable

public void destroy()

public synchronized void start()

public synchronized void stop()

// run is what the two threads run in.
public void run()

/* Sleep for 1 second at a time. Every full minute,
* restart the chimer thread. */
while( null != threadTicker )
catch( Exception e )
}
return;
}

Inter-Applet Communications Within the Browser

You can coordinate the activities of several applets by accessing and manipulating other Applet objects from within Applet code. Using inter-applet communications you could, for instance, have a 'gas-gauge' Applet report the status of another Applet, which takes a significant amount of time to initialize.

To obtain references to external Applets from within an applet you use the AppletContext's getApplet and getApplets methods. The AppletNames Applet demonstrates this technique. Once a reference to another Applet is retrieved, your applet code can access any public member variable or method of the external Applet object. This code snippet retrieves an applet named 'MyApplet' and calls one of its custom methods.

Applet applet = getAppletContext().getApplet( 'MyApplet' );
if( ! ( applet instanceof MyAppletClass ) ) return;
MyAppletClass myapplet = (MyAppletClass)applet;

myapplet.CustomFunc();

getApplet takes an applet 'name' and returns a reference to the associated Applet object. This usage model implies the browser internally stores a unique String name associated with each applet, which can be used to look up the Applet in the internal browser storage.

Similar to defining applet parameters, the method for naming applets depends on the specific browser used. For example, applet-aware World Wide Web browsers generally use a NAME field within the HTML <APPLET> container tag to associate a name with a particular Applet object. This is how an HTML document would embed an applet named 'Minnow' of class ThreeHourTouringBoat:


<APPLET src='ThreeHourTouringBoat' name='Minnow' width='100' height='100'>
<PARAM >

</APPLET>

Graphics

Applets are capable of displaying exciting and complex graphics and multimedia visuals. This section explains the specifics of graphical drawing, which is done using objects of the Graphics class and associated classes. Important concepts explaining these classes will be discussed, as well as the most common technique for visual animation, double-buffered graphics.

All graphical drawing operations in Java are performed through objects derived from the Graphics class. Whether you are drawing images downloaded from the Internet, drawing graphical primitives such as rectangles and arcs, or rendering text, all graphical operations are done using a Graphics class instance. Use of the Graphics class is not limited to Applets; it is also used for Java applications that employ graphical elements in windows.

The Graphics Class Concept

For some beginners, the concept of the Graphics class is a little diffucult to grasp. But it doesn't have to be. You can think of a Graphics object as analogous to a graphic artist's drafting table, with its associated drawing tools. It is a station of powerful tools dedicated to creating graphical images.

Each Graphics object is associated with a two-dimensional 'drawing surface,' analogous to the piece of paper on the drafting table. For example, the drawing surface can be a rectangle of a user's on-screen desktop, as is the case when dealing with Applets or Windows. Other drawing surface types could also be associated with a Graphics object. The drawing surface could be a binary image, stored in memory and never directly displayed to the user. It could also be a page in a printer, or a fax machine, or even a PostScript or other graphics-format file stored on a disk.

The 'tools' of a Graphics object, the methods of the Graphics class, are used to draw onto the associated drawing surface. Rectangles, ovals, arcs, polygons, lines, text, and images can all be drawn onto the drawing surface using the various Graphics class methods.

The internal state of a Graphics object can be described by eight state variables, which can be modified using Graphics class methods.

.  The foreground color

.  The background color

.  The current font

.  The painting mode

.  The origin of the Graphics object

.  The horizontal and vertical scaling factors

.  The 'clipping' rectangle

.  The drawing surface the Graphics object has been associated with

The Coordinate System of the Drawing Surface

All drawing surfaces use the same two-dimensional coordinate system. The X axis is in the horizontal direction of the drawing surface, and increases from left to right on the drawing surface. The Y axis is in the vertical direction, and increases from top to bottom.

The Graphics object origin defines where its X and Y axes cross, and is identified by the point (0,0). A scaling factor is assigned to both axes, which defines how quickly the coordinates increase along either axis. By default, when the Graphics object is first created, the origin lies in the upper-left corner of the drawing surface, and the scaling factor along both axes is one.

The Graphics object's X and Y axes stretch to what is essentially an infinite distance in all four directions. However, only coordinates within the Graphics object's 'clipping rectangle' are of any interest. That's because graphical operations cannot be performed outside this rectangle. Such operations will not result in any sort of error, but neither will they have any effect on the drawing surface.

The clipping rectangle of a Graphics object represents the physical boundaries of the associated drawing surface. For example, a Graphics object associated with a 100 pixel by 100 pixel rectangle of the on-screen desktop will have a clipping rectangle with a width of 100 and a height of 100. For on-screen desktop and in-memory image drawing surfaces, each Graphics coordinate represents a single pixel of the drawing surface. Hence, a 100 pixel by 100 pixel rectangle is represented by a 100 by 100 clipping rectangle in the associated Graphics object.

Obtaining Graphics Objects

A program cannot create its own Graphics objects, but instead must ask the Java runtime system to create them for specific display surfaces. Without using custom classes implementing native methods, only two types of display surfaces can be accessed through Graphics objects:

.  Sections of the on-screen desktop surface are accessed through Graphics objects passed to the update and paint methods.

.  In-memory Image objects are accessed through Graphics objects created by Image.createGraphics.

Applets inherit the update and paint methods from the Component class, which the Applet class extends. Both of these methods are called automatically by the Java runtime system when it is time to display information to the user on the desktop. (See Chapter 2, The Component Class, for an in-depth discussion of the update and paint methods). This code snippet shows how a custom applet would override the default implementation of paint to control its display surface:

public class MyApplet extends Applet



A Graphics object is automatically created by the Java runtime system and passed to paint. This Graphics object has a clipping rectangle set to the exact dimensions of the Applet's display surface. (In the cases where only a portion of the Applet must be redrawn, such as when another window temporarily covers part of the Applet's display surface, the dimensions may be smaller.)

The only other method for obtaining a Graphics object is using Image.createGraphics. An applet or application calls this method directly. The Graphics object that is returned is capable of rendering geometric primitives, text, and other Image objects onto the Image. This is useful for the so-called 'double-buffered' drawing technique, used widely to effect a smooth transition between animation frames. You'll learn more about this technique in the upcoming discussion of animation.

The Geometric Primitives

All Graphics objects are able to render several different types of geometric primitive drawing objects on a drawing surface. Table 1-2 lists the various geometric primitives and describes how they are represented by parameters to Graphics rendering methods.

Table 1-2 Geometric primitives


Primitive

Representation Through Rendering Methods


Rectangle

The point of the upper-left corner of the rectangle relative to the Graphics origin, the rectangle's width and height.

Rounded rectangle

The point of the upper-left corner of the rectangle relative to the Graphics origin, the reactangle's width and height.

3D rectangle

The point of the upper-left corner of the rectangle relative to the Graphics origin, the rectangle's width, height, and the raising or depressing implication of the beveled edges.

Oval

A bounding rectangle defines the size and shape of the oval. This rectangle is described the same way as a rectangle geometric primitive.

Arc

An arc is a section, or pie wedge, of an oval. An arc is described by the bounding rectangle of an oval, the starting angle of the arc, and the angular length of the arc.

Polygon

An ordered set of points defines the vertices of a polygon to Graphics rendering methods. Alternatively, a Polygon object can be used, though Polygons are essentially just an ordered set of vertices. Points are all relative to the Graphics object's origin.

Line segment

Two points defining the two endpoints of the line segment. Both points are relative to the Graphics object's origin.

All primitives can be rendered in either outlined or filled form, except the Line primitive, which cannot be filled. The outlined version of a primitive is rendered using the primitive's 'draw' method. For example, Graphics.drawRect will render a rectangle as two sets of parallel lines using the Graphics object's current foreground color. The 'fill' method is used to render a filled geometric primitive. Graphics.fillRect will render a solid rectangular block on the display surface using the current foreground color. Listing 1-5 is a complete example of the Nautilus applet, which uses a succession of filled and outlined arc segments (using Graphics.fillArc and Graphics.drawArc) to draw a spiral pattern. The spiral looks something like the cross-section of a nautilus shell, hence the applet class' name.

Listing 1-5 Example of the Nautilus applet

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class Nautilus extends Applet

public void paint(Graphics g)

g. setColor( Color.black );
g.drawArc( x, y, 2 * (int)flRadius,
2 * (int)flRadius, 90, nDirection * 180 );

nCenter += (int)( nDirection * (int)flRadius *
( 1 - flTightness ) );
flRadius *= flTightness;
nDirection *= -1;
}
}

The Nautilus applet requires a single parameter, the 'tightness' parameter, which describes how tightly the spiral is rendered. The 'tightness' parameter's value is a floating point number above 0 and below 1. The closer to 1 this parameter is, the tighter the spiral is. Note that, to preserve code readability, no validation of this parameter has been added. Figure 1-5 is a screenshot of the Nautilus applet run using the JDK's AppletViewer, with a 'tightness' parameter of 0.75.


Figure 1-5  Screenshot of the Nautilus applet

The Nautilus applet illustrates how to use the drawArc and fillArc methods of the Graphics class. Nautilus renders the spiral by drawing successively smaller half-circles made up of alternately colored arc wedges. The code takes advantage of the fact that the sign of the arc length parameter to Graphics.drawArc and Graphics.fillArc defines whether the arc proceeds clockwise or counter-clockwise from the starting angle.

The Painting Mode

The painting mode of a Graphics object is, by default, set to 'overwrite' mode. In this mode, all graphics are rendered by overwriting the pixels of the display surface using the Graphics object's current foreground color. You can force the Graphics object into overwrite mode using Graphics.setPaintMode. When called, this parameterless method places the Graphics into overwrite mode. Expressed pseudo-mathematically, the color of destination pixels after rendering is

colorDest(x,y) = graphics.foregroundColor

The other method of modifying a Graphics object's painting mode is Graphics.setXORMode. When called, the Graphics object uses XOR mode for rendering geometric primitives, text, or Images on the drawing surface. Three colors are combined mathematically to determine the color of destination pixels after rendering, as follows,

colorAfterRendering(x,y) = colorBeforeRendering(x,y)
⊗ graphics.foregroundColor ⊗ graphics.alternateColor

where the ⊗ symbol represents a bitwise XOR operation. The alternateColor of a Graphics object is specified as the only parameter to Graphics.setXORMode. Listing 1-6 is an example of the Ovals applet, which illustrates XOR painting mode, that can be used to draw contrasting areas of geometric primitives on the drawing surface.

Listing 1-6 Example of the Ovals applet

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class Ovals extends Applet

public void paint(Graphics g) else

g.setXORMode( Color.white );
g.fillOval( x, y, width, height );

g.setPaintMode();
g.drawOval( x, y, width, height );

flLongAxisLength *= 0.75;
flShortAxisLength *= 0.75;
fLongAxisVertical = ! fLongAxisVertical;
}

return;
}

Figure 1-6 is a screenshot of Listing 1-6, the Ovals applet, when viewed using the JDK's AppletViewer.


Figure 1-6  Screenshot of Ovals applet, demonstrating the XOR painting mode of the Graphics class

The Ovals applet uses XOR painting mode to highlight overlapping areas of oval primitives on the drawing surface. The background color of the applet's drawing surface is automatically painted light gray (Color.lightGray or RGB 192, 192, 192) by the Java runtime system.

The foreground color of the Oval's Graphics object is set to Color.black (RGB 0, 0, 0) by default. The XOR alternate color is set to Color.white (RGB 255, 255, 255), the value of the parameter to Graphics.setXORMode. Therefore, the color in which the first oval is rendered can be deduced using the formula presented earlier.

colorAfterRendering(x,y) = colorBeforeRendering(x,y)
⊗ graphics.foregroundColor ⊗ graphics.alternateColor
= (RGB 192, 192, 192) ⊗ (RGB 0, 0, 0) ⊗ (RGB 255, 255, 255)
= (RGB 63, 63, 63)

When a new oval is rendered so that it intersects an oval that has already been drawn, the intersecting area of these two ovals will be drawn with the color obtained as follows:

colorAfterRendering(x,y) = colorBeforeRendering(x,y)
⊗ graphics.foregroundColor ⊗ graphics.backgroundColor
= (RGB 63, 63, 63) ⊗ (RGB 0, 0, 0) ⊗ (RGB 255, 255, 255)
= (RGB 192, 192, 192)

In this case the result is Color.lightGray.

It is simple to show that all areas painted with the XOR painting mode using these colors an odd number of times will have the RGB values (63, 63, 63), which is Color.darkGray. All areas painted an even number of times will have the RGB values (192, 192, 192), or Color.lightGray.

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

/* Use the applet name list to initialize astrAppletNames.*/
int iNameIndex = 0;
int nStartIndex = 0;
int nNextCommaIndex = 0;

while( ( -1 != nNextCommaIndex ) && ( iNameIndex < 10 ) )
}

public void start()
}

// stop() does not need to be implemented.

public void destroy ()

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

Here are the contents of FindNamableApplet.java:

public class FindNamableApplet extends Applet implements Namable

// destroy releases references to object variables.
public void destroy()

// init fills the applet hash table, and reads in parameters.
public void init()
if( null == ( strNameToFind = getParameter( 'find' ) ) )

// Add all Namable applets to hash table.
Enumeration enumApplets = getAppletContext().getApplets();
while ( enumApplets.hasMoreElements() )
}
}

// start() attempts to find strNameToFind applet, reports results
public void start()

// 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

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 class ImageApplet extends Applet
// Load the image.
image = getAppletContext().getImage(
getDocumentBase(), strRelativeURL );
if( null == image )
System.out.println( 'Unable to load image.' );
}

public void destroy()

public void paint( Graphics g )

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


Previous

Table of Contents

Next

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

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)

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)

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)

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)

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)

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)

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

// In paint, render the image once stretched and once not
// stretched.
public void paint(Graphics g)

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)

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)

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)

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)

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)

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.

Previous

Table of Contents

Next

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)

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)

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)

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)

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)

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)

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)

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)

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()

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

public void start()

public void stop()

public void destroy()

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

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() catch (Exception e)

/*
** Retrieve the physical display size
** ( _nxPixels x _nyPixels ). If not given,
** use the Game Grid size ( _nxCells x _nyCells ).
*/
try catch (Exception e)

/*
** 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()

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()

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() catch (Exception e)

/*
** This continuous loop generates iterative
** generations of Life.
*/
while( null != _threadNextGen )

for( nI=0 ; nI<_nxCells ; nI++ )
for( nJ=0 ; nJ<_nyCells ; nJ++ )
switch( a2dnSums[ nI ][ nJ ] )
/*
** Make sure the current game grid
** has been displayed before updating
** the game grid with the next generation.
*/
while( ( ! setGameGrid( a2dfNewGrid ) ) &&
( null != _threadNextGen ) )
try 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)

public void update(Graphics 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 catch(Exception e)

_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 )

/* ********
* 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 )


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() catch (Exception e)
_imageAlive = getImage( urlAliveImage );
}

return _imageAlive;


private Image getDeadImage() 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)
}

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()

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)

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)

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.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 787
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved