
Java 1.2 Class Libraries Unleashed
by Krishna SankarEditorial Reviews
Product Details
- ISBN-13:
- 9780789712929
- Publisher:
- Que
- Publication date:
- 06/16/1998
- Series:
- Unleashed Series
- Edition description:
- Book & CD-ROM
- Pages:
- 1272
- Product dimensions:
- 7.40(w) x 9.13(h) x 2.11(d)
Read an Excerpt
[Figures are not included in this sample chapter]
Java 1.2 Class Libraries Unleashed
- 2 -
Applet
by Jeff Erickson
IN THIS CHAPTER
- java.applet
As we all know, Java applications can be embedded inside Web pages (HTML documents).Applets allow Web site developers to greatly enhance their sites by using Java'suser-friendly GUI interface objects and graphics capabilities. In fact, these aspectsof the Java language have been put to the test because most of the applets developedinvolve different types of games, advertising banners, or text animation. Most beginningJava programmers start by developing one of these kinds of applets to spice up theircompany or personal Web pages.
There are almost as many ways to write applets as there are applications. Priorto JDK 1.2, because of the "sandbox" in which Java applets are executed,there are some things applications can do that applets cannot, such as accessingdata on your hard drive or accessing servers other than the applet's host server.However, applets have provided a means for companies to provide business-criticaldata to their customers at large via the Internet. Also, by using applets to presentthat information, eye-catching representations such as graphical comparisons canbe used to make the data more meaningful than just straight numbers.
Entire sites are devoted to centralizing applet repositories and/or rating them,in a sort of ongoing competition to see who can take applets to their creative extremes.One such site is JARS (Java Applet Review Site) at http://www.jars.com/. It seemsincreasingly possible that someday just about every Web site will have some sortof Java applet included in its pages.
java.applet
package java.applet
The java.applet package is the base package necessary for developing Java applets.Any applet that a Java programmer may develop must have a base class that extendsthe java.applet.Applet class. This class also includes some basic methods that appletsmay need during the course of their existence within a Web page. In fact, there arefour methods included in the life cycle of the applet that play a major role whenit comes to including applets in a Web site (see the Applet class later in this chapter).There is an AppletContext interface for interacting with the Web page (also knownas the context or environment) in which the applet resides. The AppletStubinterface allows the applet to find out its own URL as well as its HTML page's URLlocation, including the values of any parameters that the applet may have. Finally,the AudioClip interface is useful for playing sounds while the applet is running.
java.applet: Summary
Class Names |
Interfaces |
AppletContext |
AppletStub |
AudioClip |
Classes |
Applet |
AppletContext
public interface AppletContext {...}
The AppletContext interface is of major importance when it comes to finding outinformation about the environment in which the applet resides. An applet's environmentconsists of the browser or applet viewer in which the applet is executing. It alsorelates to the document in which the applet resides, as well as any other appletsresiding in the same document. This last fact makes the use of applets in Web pageseven more intriguing. You can have more than one applet in an HTML page. Better yet,they can interact with one another to create even more complex, Internet-ready Javaapplications that consist of several smaller applications (applets) all running intandem.
With that in mind, it is easy to see how useful this interface can be. An instanceof this object can be obtained by a call to the getAppletContext() method, foundin the Applet class. Once that is accomplished, the AppletContex t object that isreturned can be used to obtain images and audio clips, show other HTML pages, grabhandles to other applets contained in the same document (environment), or show thestatus of the applet. Given that applets can show other HTML pages, you can understandthe tendency to use applets as site navigators and advertising banners. One can simplyclick inside the applet to launch the desired Web page or surf to the advertiser'ssite.
Although some of these methods can be found in the Applet class as well, the AppletContextobject must be used to show other HTML pages or get handles to other applets in thesame environment. This results from the browser-specific or applet viewer-specificnature of these types of commands. How a Web page is displayed or how handles toapplets are retrieved has to do with the internal workings of the applet environment.When an AppletContext object is desired, the environment is checked to verify whichbrowser type or applet viewer type of AppletContext object should be returned. Thisis yet another example of the usefulness of a platform-independent software developmenttool.
AppletContext: Summary
Methods/Events |
public abstract Applet getApplet(String name) |
public abstract Enumeration getApplets() |
pub lic abstract AudioClip getAudioClip(URL url) |
public abstract Image getImage(URL url) |
public abstract void showDocument(URL url) |
public abstract void showDocument(URL url, String target) |
public abstract void showStatus(String status) |
AppletContext: Methods and Events
getApplet(String)
Syntax public abstract Applet getApplet(String name)
Description Returns a handle to the applet with the given name,as it is found in the document to which this context is connected.
Parameter
String name The name of the applet to be retrieved. This value is equal to thevalue of the applet's NAME attribute, as it is found in the document to which theAppletContext is connected.
Returns Returns a handle to the applet with the specified name.
Example Given the following HTML:
<APPLET NAME="ImageLoader" ... ></APPLET> <APPLET NAME="ImageViewer"CODE="ViewImages.class" ... ></APPLET> In the Applet class ViewImages: AppletContext ac = getAppletContext();} Applet imgLoader = ac.getApplet("Image Loader");
getApplets()
Syntax public abstract Enumeration getApplets()
Description Retrieves an Enumeration object that contains handlesto all of the applets found within the document that is connected to this AppletContextobject.
Returns An Enumeration object that contains all the handlesto all of the applets in the document to which this AppletContext object is connected.See the Enumeration interface within the java.util package for details on obtainingeach individual applet handle from the Enumeration.
Example
AppletContext ac = getAppletContext(); Enumeration enum = ac.getApplets(); for ( ; enum.hasMoreElements(); ) { ((Applet)enum.nextElement()).start(); }
getAudioClip(URL)
Syntax public abstract AudioClip getAudioClip(URL url)
Description Returns an object of type AudioClip that can beused to play sounds. The sound file is retrieved from its absolute URL and must beof a format recognizable to the Java Virtual Machine.
Parameter
URL url The absolute URL of the desired audio file.
Returns Returns an AudioClip object that can be used to playsounds. See the AudioClip interface, covered later in this chapter.
Example
try { URL url = new URL("http://www.mysite.com/sounds/barking"); AudioClip audioClip = getAudioClip(url); AudioClip.play(); } catch (MalformedURLException ex) {}
getImage(URL)
Syntax public abstract Image getImage(URL url)
Description Obtains a handle to an Image object that is createdfrom the file designated by the absolute URL. This Image object can then be usedfor painting to the screen.
Parameter
URL url The absolute URL of the file whose image is to be used to create the Imageobject.
Returns An Image object that can be used for painting to thescreen.
Example
try { URL url = new URL("http://www.mysite.com/images/mypic.gif"); Image img = getImage(url); } catch (MalformedURLException ex) {}
showDocument(URL)
Syntax public abstract void showDocument(URL url)
Description Method for replacing the current Web page with theone specified by the given URL. This method may be ignored when the AppletContextobject is not connected with a browser.
Parameter
URL url The absolute URL of the Web page that is to be shown.
Example
try { showDocument(new URL("http://www.mysite.com/index.html")); } catch (MalformedURLException ex) {}
showDocument(URL, String)
Syntax public abstract void showDocument(URL url, String target)
Description Method for displaying a Web page at a given locationwithin the applet viewer or browser. An AppletContext that is not connected to abrowser may ignore this method call.
Parameters
URL url The absolute URL of the Web page to be displayed.
String target The location where the Web page is to be displayed. This parametercan have five types of values: "_self" (the current frame), "_parent"(the parent frame), "_top" ( the topmost frame), "_blank" (a newand unnamed top-level window), or name (a new top-level window that will havethe given name).
Example
try { URL url = new URL("http://www.mysite.com/index.html"); showDocument(url, "_top"); } catch (MalformedURLException ex) {}
showStatus(String)
Syntax public abstract void showStatus(String status)
Description Requests that the browser or applet viewer printthe given message to its status window. Many browsers and applet viewers providesuch a window to inform users of the status of various processes.
Parameter
String status The message to be displayed in the status window.
Example
int newScore = oldScore + 25; showStatus("SCORE: "+newScore);
AppletStub
public interface AppletStub {...}
When an applet is created, the stub for the applet is set. This stub, called anAppletStub, provides an interface between the applet and the browser environmentor applet viewer environment in which the applet is running. This interface allowsthe applet to obtain such information as the URL locations of both the applet codeand its containing document, as well as the values of any parameters that the appletmay need during its execution.
You might notice that the methods included in this interface can also be foundin some form in the Applet class. The main reason for this involves the inabilityof the user to call these AppletStub methods directly. Although an AppletStub isassigned to each applet upon initialization, it exists solely for the system's use. TThe system can use this interface to make the same method calls across many differenttypes of browsers and applet viewers. However, the specific applet environment definesexactly what must be done in order for the AppletStub to carry out the desired task.
In order to make the method call defined by one of these AppletStub methods, theprogrammer uses one of the similar methods from the Applet class. Because these methodsinvolve the environment in which the applet is contained, the Applet class asks theAppletStub to carry out the request. By making the AppletStub an interface, the Appletclass can use the same AppletStub method calls no matter what type of browser orapplet viewer environment the applet resides in. However, this also allows for attributingto the applet the correct type of AppletStub as dictated by the environment. Thereis one type of AppletStub for each type of browser environment or applet viewer environmentin which an applet can reside. All of these AppletStubs have the same method declarations,but the implementation of these methods is customized to the type of browser or appletviewer against which each AppletStub must interface. Hence, the same results cancome from the same method calls using environment-specific implementations.
AppletStub: Summary
Methods/Events |
public abstract void appletResize(int width, int height) |
public abst ract AppletContext getAppletContext() |
public abstract URL getCodeBase() |
public abstract URL getDocumentBase() |
public abstract String getParameter(String name) |
public abstract boolean isActive() |
AppletStub : Methods and Events
appletResize(int, int)
Syntax public abstract void appletResize(int width, int height)
Description Method called when the applet wants to be resized.If the browser or applet viewer allows you to change the size of the applet by draggingits edge, this method is called to enact the resizing.
Parameters
int width The new desired width for the applet.
int height The new desired height for the applet.
getAppletContext()
Syntax public abstract AppletContext getAppletContext()
Description Method for retrieving the context of the appletto which this applet stub is connected.
Returns A handle to the applet context (Web page, HTML document,and so on) of the applet to which this applet stub is connected.
getCodeBase()
Syntax publ ic abstract URL getCodeBase()
Description Retrieves a URL representing the base location ofthe code for this applet.
Returns Returns a URL representing the absolute location ofthe code for the applet.
getDocumentBase()
Syntax public abstract URL getDocumentBase()
Description Method for obtaining a handle to the base URL forthe document that contains the applet.
Returns Returns a URL representing the base location of thedocument that contains the applet.
getParameter(String)
Syntax public abstract String getParameter(String name)
Description Retrieves the string representation of the valueof one of the parameters for the applet, to which this applet stub is connected,as specified in the applet's context (containing document).
Parameter
String name The name of the parameter whose value is to be returned.
Returns The value of the parameter whose name was specifiedas the parameter name in this method.
isActive()
Syntax public abstract boolean isActive()
Description Method for determining whether or not the appletis active. An applet is activated right before its start() method is called and deactivatedright after its stop() method is called.
Returns The Boolean value is true if the applet is active, falseotherwise.
AudioClip
public interface AudioClip {...}
Given the popularity of applets in creating games, animated text, or advertisements,it woul d seem necessary for applets to play sounds. The AudioClip interface allowsthe Java programmer to use sounds and images to enhance his applets. When it comesto games, the need is obvious. Players want to hear the shots being fired and theexplosions taking place. When it comes to animated text, one can integrate the wordsonscreen with some sort of sound file that speaks the words as well. Also, advertisementbanners that grab the Web surfer's ears as well as eyes seem to get the greatestattention.
NOTE
Only Java-recognizable audio files can be used in conjunction with the AudioClip object. Audio files such as .wav or .mid are not recognizable by the Java Runtime Environment and will not work when you're trying to incorporate sounds into your applets. Only .au audio files can be used with your Java applets.
AudioClip: Summary
Methods/Events |
public abstract void loop() |
public abstract void play() |
public abstract void stop() |
AudioClip: Methods and Events
loop()
Syntax public abstract void loop()
Description Begins the continuous playing of the audio clip,from start to finish and back to the start again. This continues until it is forcedto stop by some other process (the stop() method being called, the applet being destroyed,and so on).
Example
try { Url url = new URL("http://www.mysite.com/sounds/barking"); AudioClip audioClip = newAudioClip(url); AudioClip.loop(); } catch (MalformedURLException ex) {}
play()
Syntax public abstract void play()
Description This method plays the audio clip once.
Example
try { Url url = new URL("http://www.mysite.com/sounds/barking"); AudioClip audioClip = newAudioClip(url); AudioClip.play(); } catch (MalformedURLException ex) {}
stop()
Syntax public abstract void stop()
Description This method halts the playing of the audio clip,whether its play was started by the play() or loop() methods.
Example
try { Url url = new URL("http://www.mysite.com/sounds/barking"); AudioClip audioClip = newAudioClip(url); AudioClip.stop(); } catch (MalformedURLException ex) {}
Applet
public class Applet {...}
The Applet class is easily the most important object in the java.applet package.This is the class that makes using applets in Web pages possible. Although an appletcan use many classes, the main class (the class specified in the HTML document orWeb page) must extend the Applet class. It is this extension that allows the Webbrowser or applet viewer to recognize that an applet is being included and to callthe appropriate method(s) upon execution.
When it comes to d eveloping applets for the Web, the life cycle of an applet isan important concept to understand. Every time you incorporate an applet into a Webpage, there are four methods that are called in conjunction with its use. These fourmethods, which make up the life cycle of an applet, are the init(), start(), stop(),and destroy() methods. Although the implementations of these methods in the Appletclass do nothing, if they are overridden in your applets, they will be called automaticallyas the applets are executed in the browser or applet viewer. It is important forthe applet programmer to know and understand the relationship between these methodsin order to use them efficiently.
Once the browser or applet viewer begins loading an applet, its init() methodis called. This method is called only once. It initializes any variables and preparesthe applet for execution. Other methods that the programmer wants to execute whilethe applet is loading can be called from the init() method. This allows the appletdeveloper to completely prepare the applet for execution and to get all resource-expensiveactions out of the way, ensuring optimal performance during the rest of its execution.This can include the complete loading of images, parameters, audio files, and otherdata. This works especially well for games that use images. You don't want to compromisethe playing speed of the game because it has to constantly load images during gameplay.
Once the applet is loaded and the init() method is done executing, the start()method is called. This is where separate threads may be started. Many applet gameprogrammers use this method to start the threads that control the actions of enemyships or other independently mov ing objects in games. The start() method is calledimmediately after the init() method finishes execution and every time the Web pagecontaining the applet is revisited in the browser. This fact might be important tothe cycle of your applet. For example, a game applet might be resumed when the Webpage is revisited and the start() method is called. This enables the programmer torestart gameplay when the Web surfer revisits the page that contains the game applet.
The stop() method behaves much like the start() method. It is called wheneverthe Web page containing the applet is replaced by another Web page. This featureis useful when there are applet actions that you want to halt when the applet isnot being viewed. For example, a game programmer wouldn't want the player to losea life because of something that occurred while the applet was running on a Web pagein the background. By forcing the game to pause when the player links to a differentpage, such instances can be avoided.
Finally, the destroy() method reacquires the applet's system resources once theapplet is no longer being used. This is the last method called and it is called onlyonce, before an applet is removed by the system. This occurs when the browser orapplet viewer being used to view the applet and its containing document are closed.At that point, all applet destroy() methods are called to reclaim the system resourcesthat are no longer needed by those applets. Applet developers can use their own overriddendestroy() method to kill any threads used by the applet or conduct any cleanup theydeem necessary before the applet's resources are reclaimed by the system.
Applet: Summary
Methods/Events
public Applet()
public void destroy()
public AppletContext getAppletContext()
public String getAppletInfo()
public AudioClip getAudioClip(URL url)
public AudioClip getAudioClip(URL url, String name)
public URL getCodeBase()
public URL getDocumentBase()
public Image getImage(URL url)
public Image getImage(URL url, String name)
public Locale getLocale()
public String getParameter(String name)
public String[][] getParameterInfo()
public void init()
public boolean isActive()
public static final AudioClip
newAudioClip(URL ur
public void play(URL url)
public void play(URL url, String name)
public void resize(Dimension d)
public void resize(int width, int height)
public final void setStub(AppletStub stub)
public void showStatus(String msg)
public void start()
public void stop()
Applet: Example
An example is necessary to demonstrate some of the features of applets. Becauseof the possibilities inherent in the development of applets, given that they canuse just about the entire API in their functionality, the following applet demonstratesonly the merest subset of the available features.
Place the following text into a file called ScrollingText.html:
<HTML><HEAD><TITLE>Text Scroller</TITLE></HEAD><BODY><APPLET CODE="ScrollingText.class" WIDTH="100" HEIGHT="50"><PARAM NAME="text" VALUE="Java Class Libraries Unleashed"></APPLET></BODY></HTM L>
Place the following code in a file called ScrollingText.java:
import java.applet.*;import java.awt.*;public class ScrollingText extends Applet implements Runnable { FontMetrics fm; String textToScroll; Thread thisThread; int textX, textY, textWd; public void init() { textToScroll = getParameter("text"); if (textToScroll == null) { textToScroll = "--- NO MESSAGE ---"; } fm = getFontMetrics(getFont()); textX = size().width; textY = ((size().height - fm.getHeight()) >> 1) + fm.getHeight(); textWd = fm.stringWidth(textToScroll); } public void start() { if (thisThread == null) { thisThread = new Thread(this); } thisThread.start(); } public void paint(Graphics g) { g.setColor(Color.blue); g.drawString(textToScroll, textX, textY); } public void run() { while (true) { textX -= 5; if (textX + textWd < 0) { textX = size().width; } try { thisThread.sleep(200); } catch (InterruptedException ie) { System.out.println("Interrupted Exception ... "+ie); } repaint(); } }}
Then try running the applet with your favorite Web browser or applet viewer. Youwill see the text given in the PARAM tag "text" scroll across the appletwindow. This applet demonstrates applets' capability to use parameters, threads,and even some simple animation. You could quite easily expand this applet to enhanceits functionality. You could add other parameters to set the text's color or movements peed (number of pixels the text moves each time). You could use images for the backgroundor have an image scroll across the screen. You could also add the stop() method tofreeze the animation while the page is not being viewed. In short, this example shoulddemonstrate the possibilities that applets bring to the World Wide Web.
Applet: Methods and Events
Applet()
Syntax public Applet()
Description Method for constructing a new instance of an Appletobject. Using this constructor allows Java applications to take advantage of someof the functionality that used to be reserved for applets.
Returns A handle to a new instance of an Applet object.
Example Applet applet = new Applet();
destroy()
Syntax public void destroy()
Description This method is called to inform the applet thatit is about to be destroyed, and that it should relinquish any resources that itis using. The implementation of this method as found in the Applet class itself doesnothing.
Example
if (imgLoaded) { Applet applet = getAppletContext().getApplet("ImageLoader");applet.destroy(); }
getAppletContext()
Syntax public AppletContext getAppletContext()
Description Retrieves a handle to the environment in which theapplet is contained.
Returns An instance of an AppletContext object that can be usedto interface with the environment in which the applet is contained.
Example
AppletContext ac = getAppletContext(); ac .showStatus("Please wait... Loadingimages...");
getAppletInfo()
Syntax public String getAppletInfo()
Description Method for returning information about the author,version, and copyright of the applet. This method needs to be overridden in orderto return this information because the implementation of this method as found inthe Applet class returns null.
Returns A String object representing the author, version, andcopyright information for this applet.
Example
public String getAppletInfo() { return "Author: Jeff Erickson\n" + "Version: 1.2\n" + "Copyright 1998"; }
getAudioClip(URL)
Syntax public AudioClip getAudioClip(URL url)
Description Retrieves a handle to an object of type AudioClipthat can be used for playing sounds. The audio file must be of a type recognizableby the Java Virtual Machine.
Parameter
URL url The location of the audio file that will be used to create the AudioClipobject returned by this method.
Returns An object of type AudioClip that can be used to playsounds.
Example
try { URL url = new URL("http://www.mysite.com/sounds/siren"); AudioClip audio = getAudioClip(url); audio.loop(); } catch (MalformedURLException ex) {}
getAudioClip(URL, String)
Syntax public AudioClip getAudioClip(URL url, String name)
Description Retrieves a handle to an object of type AudioClipthat can be used for playing sounds. The audio file must be of a type recognizableby the Java Virtual Machine.
Parameters
URL url An absolute URL that forms the base location of the audio clip.
String name The location of the audio clip, relative to the base URL.
Returns An object of type AudioClip that can be used for playingsounds.
Example
try { URL url = new URL("http://www.mysite.com/sounds/"); AudioClip audio = getAudioClip(url, "siren"); audio.loop(); } catch (MalformedURLException ex) {}
getCodeBase()
Syntax public URL getCodeBase()
Description Method for obtaining a handle to a URL object thatrepresents the absolute location of the applet's code.
Returns An absolute URL indicating the location of the codefor the applet.
Example
URL codeBaseURL = getCodeBase(); Image img = getImage(codeBaseURL, "door.jpg");
getDocumentBase()
Syntax public URL getDocumentBase()
Description This method retrieves a handle to an object of typeURL that represents the absolute location of the document that contains the applet.
Returns A URL object representing the absolute location of thedocument that contains the applet (this document is the applet's context or environment).
Example
URL baseURL = getDocumentBase(); AppletContext ac = getAppletContext(); ac.showDocument(baseURL, "home.html");
getImage(URL)
Syntax public Image getImage(URL url)
Description &nbs p;Method for retrieving an object of type Image thatcan be used to paint an image to the screen. This method returns automatically whetheror not the image information exists.
Parameter
URL url The absolute URL of the data for the image to be retrieved.
Returns An Image object that can be used to draw a picture tothe screen.
Example
Image img = null; try { URL url = new URL("http://www.mysite.com/images/pic1.gif"); img = getImage(url); } catch (MalformedURLException ex) {}
getImage(URL, String)
Syntax public Image getImage(URL url, String name)
Description Method for retrieving an object of type Image thatcan be used to paint an image to the screen. This method returns automatically whetheror not the image information exists.
Parameters
URL url The base location of the file containing the data to be retrieved forthe Image.
String name Relative to the base URL location, the location of the file containingthe data to be retrieved for the Image.
Returns An Image object that can be used for drawing picturesto the screen.
Example
Image img[] = new Image[10]; try { URL url = new URL("http://www.mysite.com/images/"); for (int i = 0; i < 10; i++) { img[i] = getImage(url, "pic"+i+".gif"); } } catch (MalformedURLException ex) {}
getLocale()
Syntax public Locale getLocale()
Description Method for retrieving a handle to an object of typeLocale. If the Locale for this applet has been set, tha t Locale is returned. If theLocale has not been set, the default Locale is returned.
Returns The Locale for the applet that represents the user'sgeographical, political, or cultural region.
Example
Locale locale = getLocale(); System.out.println("Locale Language: "+locale.getLanguage());
getParameter(String)
Syntax public String getParameter(String name)
Description Retrieves the string representation of the valueof one of the parameters for the applet, as specified in the applet's context. Whenan HTML document is the applet's context, these parameters are specified in the HTMLcode between the <APPLET> and </APPLET> tags for the applet in question.
Parameter
String name The name of the parameter whose value is to be returned.
Returns The value of the parameter whose name was specifiedas the parameter name in this method.
Example Given the HTML document code:
<APPLET CODE="MyApplet.class" WIDTH="200" HEIGHT="200"> <PARAM NAME="color" VALUE="blue"> </APPLET> and the `MyApplet' Code: String textColor = appletStub.getParameter("color"); The value of `textColor' would be `blue'
getParameterInfo()
Syntax public String[][] getParameterInfo()
Description Returns a two-dimensional array of information,specific to the parameters that are recognized by this applet. The implementationof this method in the Applet class returns null, so this method must be overr idden.In doing so, each element in the String array should contain an array of three strings.The first element should contain the name of the parameter, the second element shouldcontain the type of parameter it is, and the third element should contain a descriptionof the parameter's purpose.
Returns A two-dimensional array of strings that can help explainthe number of parameters used, as well as the name, type, and description of eachparameter.
Example
public String[][] getParameterInfo() {String paramInfo = { {"bgColor", "Color", "The applet's background color"}, {"fontSize", "int", "The size of the font"}, {"text", "String", "Text for use in the applet"} }; return paramInfo; }
init()
Syntax public void init()
Description Method to inform the applet that it has been loadedinto the system. The implementation of this method in the Applet class does nothing.
Example
AppletContext ac = getAppletContext(); Applet imgLoaderApplet = ac.getApplet("ImageLoader"); imgLoaderApplet.init();
isActive()
Syntax public boolean isActive()
Description Method for determining whether or not the appletis active. An applet becomes active right before its start() method is called, andit becomes inactive right after its stop() method is called.
Returns The Boolean value is true if the applet is active, falseotherwise.
Example
// Pause until the Applet is re activated if (!isActive()) { Thread.sleep(200); }
newAudioClip(URL)
Syntax public static final AudioClip newAudioClip(URL url)
Description This method allows Java applications that are notapplets to use sounds just like applets can. Once the AudioClip object is createdfrom the audio file at the specified URL, it can be used to play the file.
Parameter
URL url The absolute URL of the location that contains the audio file.
Returns An object of type AudioClip that can be used to playsounds.
Example
try { URL url = new URL("http://www.mysite.com/sounds/chirp"); AudioClip chirp = newAudioClip(url); chirp.loop(); } catch (MalformedURLException ex) {}
play(URL)
Syntax public void play(URL url)
Description Plays the audio clip found at the location specifiedby the absolute URL. This allows applets to play sounds without actually having tofirst obtain a handle to an AudioClip object.
Parameter
URL url The absolute URL indicating the location of the audio clip to be played.
Example
try { play(new URL("http://www.mysite.com/sounds/finale")); } catch (MalformedURLException ex) {}
play(URL, String)
Syntax public void play(URL url, String name)
Description Plays the audio clip found at the location specifiedby the absolute URL and the relative name parameters. This allows applets to playsounds without actually having to first obtain a handle to an AudioClip object.
Paramete rs
URL url The absolute URL indicating the base location of the audio clip to beplayed.
String name The location relative to the base URL for the audio clip to be played.
Example
try { if (score >= 10000) play(new URL("http://www.mysite.com/sounds/"), "finale1"); else play(new URL("http://www.mysite.com/sounds/"), "finale2"); } catch (MalformedURLException ex) {}
resize(Dimension)
Syntax public void resize(Dimension d)
Description Method for requesting that the applet be resized.If you are viewing the applet in an applet viewer, this method can be called whilethe applet is running to resize the window in which the applet resides. However,if the applet is being viewed in a browser, such as Netscape or Internet Explorer,calling this method will have no effect.
Parameter
Dimension d Dimension object that contains the width and height to which the appletshould be resized.
Example
Dimension d = new Dimension(200, 200); resize(d);
resize(int, int)
Syntax public void resize(int width, int height)
Description Method for requesting that the applet be resized.If you are viewing the applet in an applet viewer, this method can be called whilethe applet is running to resize the window in which the applet resides. However,if the applet is being viewed in a browser, such as Netscape or Internet Explorer,calling this method will have no effect.
Parameters
int width The width to which the applet should be resized.
in t height The height to which the applet should be resized.
Example resize(200, 200);
setStub(AppletStub)
Syntax public final void setStub(AppletStub stub)
Description Method for setting the applet's stub. This is doneautomatically by the system.
Parameter
AppletStub stub The new stub to serve as an interface to the applet's environment.
showStatus(String)
Syntax public void showStatus(String msg)
Description Shows a message in the applet viewer's or browser'sstatus window. This is useful for telling users the status of the applet (whetherit's a game score, the status of a loading image, or otherwise).
Parameter
String msg The message to be displayed in the status window.
Example
while (!g.drawImage(img, 0, 0, null)) { showStatus("Please wait. Loading images..."); }
start()
Syntax public void start()
Description Method called right after the init() method to informthe applet that it should begin execution. The implementation of this method in theApplet class does nothing.
Example
if (gameInitialized) { start(); }
stop()
Syntax public void stop()
Description Method called to inform the applet that it shouldstop its execution. The implementation of this method in the Applet class does nothing.
Example
if (livesLeft == 0) { stop(); }
Meet the Author
Customer Reviews
Average Review: