Sie sind auf Seite 1von 26

Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 1 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.

html 3/23/01 [Figures are not included in this sample chapter] Java 1.2 Class Libraries Unleashed -2Applet by Jeff Erickson IN THIS CHAPTER l 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 s user-friendly GUI interface objects and graphics capabilities. In fact, these aspects of the Java language have been put to the test because most of the applets developed involve different types of games, advertising banners, or text animation. Most beginning Java programmers start by developing one of these kinds of applets to spice up their company or personal Web pages. There are almost as many ways to write applets as there are applications. Prior to 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 accessing data 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-critical data to their customers at large via the Internet. Also, by using applets to present that information, eyecatching representations such as graphical comparisons can be 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 seems increasingly possible that someday just about every Web site will have some sort of 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 extends the java.applet.Applet class. This class also includes some basic methods that applets may need during the course of their existence within a Web page. In fact, there are four methods included in the life cycle of the applet that play a major role when it 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 known as the context or environment) in which the applet resides. The AppletStub interface allows the applet to find out its own URL as well as its HTML page s URL location, including the values of any parameters that the applet may have. Finally, the AudioClip interface is useful for playing sounds Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 2 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 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 out information about the environment in which the applet resides. An applet s environment consists of the browser or

applet viewer in which the applet is executing. It also relates to the document in which the applet resides, as well as any other applets residing in the same document. This last fact makes the use of applets in Web pages even 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 Java applications that consist of several smaller applications (applets) all running in tandem. With that in mind, it is easy to see how useful this interface can be. An instance of this object can be obtained by a call to the getAppletContext() method, found in the Applet class. Once that is accomplished, the AppletContext object that is returned can be used to obtain images and audio clips, show other HTML pages, grab handles to other applets contained in the same document (environment), or show the status of the applet. Given that applets can show other HTML pages, you can understand the tendency to use applets as site navigators and advertising banners. One can simply click inside the applet to launch the desired Web page or surf to the advertiser s site. Although some of these methods can be found in the Applet class as well, the AppletContext object must be used to show other HTML pages or get handles to other applets in the same environment. This results from the browser-specific or applet viewer-specific nature of these types of commands. How a Web page is displayed or how handles to applets 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 which browser type or applet viewer type of AppletContext object should be returned. This is yet another example of the usefulness of a platform-independent software development tool. AppletContext: SummaryJava 1.2 Class Libraries Unleashed - CH 2 - Applet Page 3 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Methods/Events public abstract Applet getApplet(String name) public abstract Enumeration getApplets()

public 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 the value of the applet's NAME attribute, as it is found in the document to which the AppletContext 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("ImageLoader"); getApplets() Syntax public abstract Enumeration getApplets() Description Retrieves an Enumeration object that contains handles to all of the applets found within the document that is connected to this AppletContext object. Returns An Enumeration object that contains all the handles to all of the applets in the document to which this AppletContext object is connected. See the Enumeration interface within the java.util Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 4 of 20

file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 package for details on obtaining each 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 be used to play sounds. The sound file is retrieved from its absolute URL and must be of 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 play sounds. 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 created from the file designated by the absolute URL. This Image object can then be used for painting to the screen. Parameter URL url The absolute URL of the file whose image is to be used to create the Image object. Returns An Image object that can be used for painting to the screen. 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 the one specified by the given URL. Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 5 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 This method may be ignored when the AppletContext object 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 location within the applet viewer or browser. An AppletContext that is not connected to a browser 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 parameter can have five types of values: "_self" (the current frame), "_parent" (the parent frame), "_top" (the topmost frame), "_blank" (a new and unnamed top-level window), or name (a new top-level window that will have the 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 print the given message to its status window. Many browsers and applet viewers provide such 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); AppletStubJava 1.2 Class Libraries Unleashed - CH 2 - Applet Page 6 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 public interface AppletStub {...} When an applet is created, the stub for the applet is set. This stub, called an AppletStub, provides an interface between the applet and the browser environment or applet viewer environment in which the applet is running. This interface allows the applet to obtain such information as the URL locations of both the applet code and its containing document, as well as the values of any parameters that the applet may need during its execution. You might notice that the methods included in this interface can also be found in some form in the Applet class. The main reason for this involves the inability of the user to call these AppletStub methods directly. Although an AppletStub is assigned to each applet upon initialization, it exists solely for the system s use. The system can use this interface to make the same method calls across many different types of browsers and applet viewers. However, the specific applet environment defines exactly 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, the programmer uses one of the similar methods from the Applet class. Because these methods involve the environment in

which the applet is contained, the Applet class asks the AppletStub to carry out the request. By making the AppletStub an interface, the Applet class can use the same AppletStub method calls no matter what type of browser or applet viewer environment the applet resides in. However, this also allows for attributing to the applet the correct type of AppletStub as dictated by the environment. There is one type of AppletStub for each type of browser environment or applet viewer environment in 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 applet viewer against which each AppletStub must interface. Hence, the same results can come from the same method calls using environment-specific implementations. AppletStub: Summary Methods/Events public abstract void appletResize(int width, int height) public abstract 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)Java 1.2 Class Libraries Unleashed - CH 2 Applet Page 7 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 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 dragging its 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 applet to 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 public abstract URL getCodeBase() Description Retrieves a URL representing the base location of the code for this applet. Returns Returns a URL representing the absolute location of the code for the applet. getDocumentBase() Syntax public abstract URL getDocumentBase() Description Method for obtaining a handle to the base URL for the document that contains the applet. Returns Returns a URL representing the base location of the document that contains the applet. getParameter(String) Syntax public abstract String getParameter(String name) Description Retrieves the string representation of the value of 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.Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 8 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Returns The value of the parameter whose name was specified as the parameter name in this method.

isActive() Syntax public abstract boolean isActive() Description Method for determining whether or not the applet is active. An applet is activated right before its start() method is called and deactivated right after its stop() method is called. Returns The Boolean value is true if the applet is active, false otherwise. AudioClip public interface AudioClip {...} Given the popularity of applets in creating games, animated text, or advertisements, it would seem necessary for applets to play sounds. The AudioClip interface allows the Java programmer to use sounds and images to enhance his applets. When it comes to games, the need is obvious. Players want to hear the shots being fired and the explosions taking place. When it comes to animated text, one can integrate the words onscreen with some sort of sound file that speaks the words as well. Also, advertisement banners that grab the Web surfer's ears as well as eyes seem to get the greatest attention. 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 Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 9 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 again. This continues until it is forced to 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 applet can use many classes, the main class (the class specified in the HTML document or Web page) must extend the Applet class. It is this extension that allows the Web browser or applet viewer to recognize that an applet is being included and to call the appropriate method(s) upon execution. When it comes to developing applets for the Web, the life cycle of an applet is an important concept to understand. Every time you incorporate an applet into a Web page, there are four methods that are called in conjunction with its use. These four methods, 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 Applet class do nothing, if they are overridden in your applets, they will be called automatically as the applets are executed in the browser or applet viewer. It is important for the applet programmer to know and understand the relationship between these methods in order to use them efficiently.Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 10 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Once the browser or applet viewer begins loading an applet, its init() method is called. This method is called only once. It initializes any variables and prepares the applet for execution. Other methods that the programmer wants to execute while the applet is loading can be called from the init() method. This allows the applet developer to completely prepare the applet for execution and to get all resource-expensive actions 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 other data. This works especially well for games that use images. You don t want to compromise the 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 game programmers use this method to start the

threads that control the actions of enemy ships or other independently moving objects in games. The start() method is called immediately after the init() method finishes execution and every time the Web page containing the applet is revisited in the browser. This fact might be important to the cycle of your applet. For example, a game applet might be resumed when the Web page is revisited and the start() method is called. This enables the programmer to restart 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 whenever the Web page containing the applet is replaced by another Web page. This feature is useful when there are applet actions that you want to halt when the applet is not being viewed. For example, a game programmer wouldn t want the player to lose a life because of something that occurred while the applet was running on a Web page in the background. By forcing the game to pause when the player links to a different page, such instances can be avoided. Finally, the destroy() method reacquires the applet s system resources once the applet is no longer being used. This is the last method called and it is called only once, before an applet is removed by the system. This occurs when the browser or applet 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 resources that are no longer needed by those applets. Applet developers can use their own overridden destroy() method to kill any threads used by the applet or conduct any cleanup they deem 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()Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 11 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 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. Because of the possibilities inherent in the development of applets, given that they can use just about the entire API in their

functionality, the following applet demonstrates only 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> </HTML>Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 12 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 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. You will see the text given in the PARAM tag "text" scroll across the applet window. This applet demonstrates applets capability to use parameters, threads, and even some simple animation. You could quite easily expand this applet to enhance its functionality. You could add other parameters to set the text s color or movement speed (number of pixels the text moves each time). You could use images for the background or have an image scroll across the screen. You could also add the stop() method to freeze the animation while the page is not being viewed. In short, this example should demonstrate the possibilities that applets bring to the World Wide Web. Applet: Methods and Events Applet()Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 13 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Syntax public Applet() Description Method for constructing a new instance of an Applet object. Using this constructor allows Java applications to take advantage of some of 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 that it is about to be destroyed, and that it should relinquish any resources that it is using. The implementation of this method as found in the

Applet class itself does nothing. Example if (imgLoaded) { Applet applet = getAppletContext().getApplet("ImageLoader"); applet.destroy(); } getAppletContext() Syntax public AppletContext getAppletContext() Description Retrieves a handle to the environment in which the applet is contained. Returns An instance of an AppletContext object that can be used to interface with the environment in which the applet is contained. Example AppletContext ac = getAppletContext(); ac.showStatus("Please wait... Loading images..."); 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 order to return this information because the implementation of this method as found in the Applet class returns null. Returns A String object representing the author, version, and copyright information for this applet. Example public String getAppletInfo() { return "Author: Jeff Erickson\n" +Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 14 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 "Version: 1.2\n" + "Copyright 1998"; } getAudioClip(URL) Syntax public AudioClip getAudioClip(URL url) Description Retrieves a handle to an object of type AudioClip that can be used for playing sounds. The audio file must be of a type recognizable by the Java Virtual Machine. Parameter

URL url The location of the audio file that will be used to create the AudioClip object returned by this method. Returns An object of type AudioClip that can be used to play sounds. 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 AudioClip that can be used for playing sounds. The audio file must be of a type recognizable by 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 playing sounds. 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 that represents the absolute location of the applet's code.Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 15 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Returns An absolute URL indicating the location of the code for 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 type URL that represents the absolute location of the document that contains the applet. Returns A URL object representing the absolute location of the document 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 Method for retrieving an object of type Image that can be used to paint an image to the screen. This method returns automatically whether or 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 to the 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 that can be used to paint an image to the screen. This method returns automatically whether or not the image information exists. ParametersJava 1.2 Class Libraries Unleashed - CH 2 - Applet Page 16 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 URL url The base location of the file containing the data to be retrieved for the Image. String name Relative to the base URL location, the location of the file containing the data to be retrieved for the Image. Returns An Image object that can be used for drawing pictures to 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 getLocale() Syntax public Locale getLocale() Description Method for retrieving a handle to an object of type Locale. If the Locale for this applet has been set, that Locale is returned. If the Locale has not been set, the default Locale is returned. Returns The Locale for the applet that represents the user's geographical, 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 value of one of the parameters for the applet, as specified in the applet's context. When an HTML document is the applet's context, these parameters are specified in the HTML code 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 specified as 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 Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 17 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 getParameterInfo() Syntax public String[][] getParameterInfo() Description Returns a two-dimensional array of information, specific to the parameters that are recognized by this applet. The implementation of this method in the Applet class returns null, so this method must be overridden. 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 should contain the type of parameter it is, and the third element should contain a description of the parameter's purpose. Returns A two-dimensional array of strings that can help explain the number of parameters used, as well as the name, type, and description of each parameter. 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 loaded into 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 applet is active. An applet becomes active right before its start() method is called, and it becomes inactive right after its stop() method is called. Returns The Boolean value is true if the applet is active, false otherwise. Example // Pause until the Applet is reactivated if (!isActive()) { Thread.sleep(200); } newAudioClip(URL)Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 18 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 Syntax public static final AudioClip newAudioClip(URL url) Description This method allows Java applications that are not applets to use sounds just like applets can. Once the AudioClip object is created from 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 play sounds.

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 specified by the absolute URL. This allows applets to play sounds without actually having to first 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 specified by the absolute URL and the relative name parameters. This allows applets to play sounds without actually having to first obtain a handle to an AudioClip object. Parameters URL url The absolute URL indicating the base location of the audio clip to be played. String name The location relative to the base URL for the audio clip to be played. ExampleJava 1.2 Class Libraries Unleashed - CH 2 - Applet Page 19 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 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 while the 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 applet should 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 while the 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. int 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 done automatically by the system.

Parameter AppletStub stub The new stub to serve as an interface to the applet's environment.Java 1.2 Class Libraries Unleashed - CH 2 - Applet Page 20 of 20 file://J:\prodinfo\MEMBERS\MA\iq571.html 3/23/01 showStatus(String) Syntax public void showStatus(String msg) Description Shows a message in the applet viewer's or browser's status window. This is useful for telling users the status of the applet (whether it'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 inform the applet that it should begin execution. The implementation of this method in the Applet class does nothing. Example if (gameInitialized) { start(); } stop() Syntax public void stop() Description Method called to inform the applet that it should stop its execution. The implementation of this method in the Applet class does nothing. Example if (livesLeft == 0) { stop(); }

Das könnte Ihnen auch gefallen