📄 ch6.htm
字号:
is also a good place to begin threads since their existence isalso not confined to the page where they began.<LI><TT><B>stop()</FONT></B></TT> This methodis called whenever the user leaves a page-it is the converse ofthe <TT>start()</TT> method. Therefore,it's a good place to hide frames and terminate threads.<LI><TT><B>destroy()</FONT></B></TT><B> </B>The<TT>destroy()</TT> method is calledwhenever the applet is being shut down. Typically, this will occurwhen the browser is being closed, although there could be othercircumstances that could lead to <TT>destroy()</TT>being invoked. This method is a good place to do some cleanup.However, since it's unpredictable when <TT>destroy()</TT>will be called, it should be used with some discretion.</UL><P>The example that follows shows how these four methods work withthe Frame class, providing an interesting insight into their behavior.Listing 6.1 shows code used to create a simple frame from an applet.The <TT>init()</TT> and <TT>destroy()</TT>methods print out their invocations to standard output so theirbehavior can be tracked.<HR><BLOCKQUOTE><B>Listing 6.1. An applet that creates Frames at initialization.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.applet.Applet;<BR><BR>// This applet illustrates how Frames work <BR>// with basic Applet methods<BR>public class AppletBasics extends Applet {<BR> Frame f;<BR> // Called once and only once upon<BR> // applet initialization<BR> public void init() {<BR> System.out.println("InApplet init. Create frame!");<BR> // Create a frame and makeit visible...<BR> f = new Frame("AppletBasics test!");<BR> f.resize(300,200);<BR> f.show();<BR> }<BR><BR> // Applet destroyed. Browser probablyshutting down...<BR> public void destroy() {<BR> // Destroy the frame<BR> f.dispose();<BR> System.out.println("In applet destroy!");<BR> }<BR></TT>}</BLOCKQUOTE><HR><P>Frame's behavior is curious. If you leave the page where the Framewas created, the Frame will still be active and visible. Thismay or may not be the behavior you want. Furthermore, if you removethe <TT>dispose()</TT> method fromthe destroy call, you can get some downright undesirable behavior.In some browsers, you could create multiple instances of the frameby reopening its location reference. In Figure 6.1, three instancesof the frame were created by going to its location several times.<P><A HREF="f6-1.gif" ><B>Figure 6.1 : </B><I>Creating multiple frames by reloading its location </I></A><P>Listing 6.2 gives the applet its desirable behavior of hidingthe frame every time you leave the page and redisplaying it whenyou come back. It simply calls the <TT>show()</TT>method of the Frame class in an overridden Applet <TT>start()</TT>method and hides the Frame in an overridden <TT>stop()</TT>method.<HR><BLOCKQUOTE><B>Listing 6.2. An applet that displays the frame only when youare on the applet's page.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.applet.Applet;<BR><BR>// This applet illustrates how Frames work <BR>// with basic Applet methods<BR>public class AppletBasics extends Applet {<BR> Frame f;<BR> // Called once and only once upon<BR> // applet initialization<BR> public void init() {<BR> System.out.println("InApplet init. Create frame!");<BR> // Create a frame and makeit visible...<BR> f = new Frame("AppletBasics test!");<BR> f.resize(300,200);<BR> }<BR><BR> // Move the show to the start method so theFrame<BR> // disappears when you leave the page...<BR> public void start() {<BR> System.out.println("Inapplet start!");<BR> f.show();<BR> }<BR><BR> // Hide the frame when you leave the page...<BR> public void stop() {<BR> System.out.println("Inapplet stop!");<BR> f.hide();<BR> }<BR><BR> // Applet destroyed. Browser probablyshutting down...<BR> public void destroy() {<BR> f.dispose();<BR> System.out.println("Inapplet destroy!");<BR> }<BR>}</TT></BLOCKQUOTE><HR><P>It is worth spending a few minutes playing around with this appletto get a full understanding of how these methods work. Try discardingor moving the code to see what will happen.<H2><A NAME="AppletsandHTML"><FONT SIZE=5 COLOR=#FF0000>Appletsand HTML</FONT></A></H2><P>A special HTML tag is used for including applets within a Webpage. The <APPLET> tag is used to indicate that an appletis to be run at the current location in the HTML. The typicalsyntax for the tag would be like the following:<BLOCKQUOTE><TT><APPLET CODE="AppletTags"WIDTH=200 HEIGHT=60><BR></APPLET></TT></BLOCKQUOTE><P>The <APPLET> tag has required attributes, as this exampleshows. The CODE attribute states the name of the class file thatruns the applet. The "AppletTags" class of this examplewill be a subclass of Applet. Java will look in the path specifiedin the <TT>CLASSPATH</TT> variableto find the class. The <TT>WIDTH</TT>and <TT>HEIGHT</TT> parameters describethe bounding region of the applet. These are also required andneed to be set to the proper values if the applet is to look theway you want. Instances of the Window class, like frames, canappear outside this region. The </APPLET> tag is used toindicate the end of the HTML applet block.<P>An interesting characteristic of this <APPLET> tag pairis that any non-tagged text appearing within this block will appearin a browser that supports Java, but will not for non-Java-capablebrowsers. This feature can be used to indicate that a page ismissing some functionality because the browser does not supportJava. For example, the modifications of the previous lines<BLOCKQUOTE><TT><APPLET CODE="AppletTags"WIDTH=200 HEIGHT=60><BR>You need to get a Java capable browser!<BR></APPLET></TT></BLOCKQUOTE><P>will show the appropriate message for a browser that does notsupport Java.<P>The <APPLET> tag supports a couple of other optional attributes.The ALIGN attribute is used to control the alignment of the appleton the page. This attribute has about half a dozen possible values,including <TT>LEFT</TT>, <TT>RIGHT</TT>,<TT>TOP</TT>, <TT>MIDDLE</TT>,and so forth. The ALIGN attribute can be used to wrap text aroundan applet. The accompanying CD-ROM has a variation of the followingexample that uses the ALIGN attribute to right-align the text.(The file, which is in the <A HREF="ch6.htm" >Chapter 6</A> directory,is launched by <TT>appletrighttags.html</TT>.)The HSPACE and VSPACE attributes use the pixel values to controlspacing between the applet and the text around it.<P>The CODEBASE attribute can be used to complement the CODE attribute.It specifies an alternative path where the class specified byCODE can be found.<P>Programmers will find the <PARAM> tag to be of the mostinterest. It is a separate tag from <APPLET>, although itappears within its block. The <PARAM> tag consists of NAME-VALUEattribute pairs that describe the name of a parameter variableand its corresponding value. It can appear multiple times withthe <APPLET> block. This is illustrated with an example.<P>Figure 6.2 shows a page displaying a couple of strings of text.The first line is produced by the normal HTML text mechanism,but the second line is written out by an applet. Within the <APPLET>and </APPLET> tag pair are two parameters. The first one,with the NAME of "text," is used by the applet to displaythe second line of text, which is specified by the VALUE attribute.The second parameter, called "unused," is ignored butshows how multiple parameters can be included in the <APPLET>block.<P><A HREF="f6-2.gif" ><B>Figure 6.2 : </B><I>An applet that uses the PARAMETER attribute to specify display text </I></A><HR><BLOCKQUOTE><B>Listing 6.3. An HTML listing of Figure 6.2 illustrating theuse of <APPLET> and <PARAMETER> tags.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT><TITLE>Applet Tags First Test</TITLE><BR><HR><BR><P> This is HTML text.<BR><P><BR><P><BR><APPLET CODE="AppletTags" WIDTH=200 HEIGHT=60><BR><PARAM NAME=text VALUE="This is the AppletTags applet"><BR><PARAM NAME=unused VALUE="This doesn't matter"><BR>You need to get a Java capable browser!<BR></APPLET><BR><P><BR><HR></TT></BLOCKQUOTE><HR><P>The Applet class uses the <PARAMETER> tags through the <TT>getParameter()</TT>method. This method takes a String indicating the NAME attributeand returns a String specifying the VALUE attribute. It will returnnull if the NAME attribute is not found. Listing 6.4 shows thecode that uses the <TT>getParameter()</TT>method to display the second line of text in Figure 6.2.<HR><BLOCKQUOTE><B>Listing 6.4. Applet code of Figure 6.2 illustrating the useof parameters.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.applet.Applet;<BR><BR>// This applet takes an applet parameter<BR>// and displays it...<BR>public class AppletTags extends Applet {<BR> String text;<BR> public void init() {<BR> // Get the text to be displayedfrom<BR> // the applet tag parameters...<BR> if ((text = getParameter("text"))== null)<BR> text= "Parameter not found!";<BR> }<BR><BR> // Display the parameter text...<BR> public void paint(Graphics g) {<BR> g.drawString(text,10,10);<BR> }<BR><BR>}</TT></BLOCKQUOTE><HR><P>The project at the end of this chapter makes extensive use ofparameters and gives you a more involved illustration of how parameterscan be constructed in the HTML and read in by the applet.<H2><A NAME="AppletsandImages"><FONT SIZE=5 COLOR=#FF0000>Appletsand Images</FONT></A></H2><P>The Applet class provides some basic methods for loading an imageinto memory. Both of these methods return an instance of an implementationof the Image class. The Image class is an abstract class providingmethods that define the kind of behaviors an image should have.The underlying implementation of images in the JDK is somewhatcomplex. However, it isn't necessary to understand how this worksto display images. Consequently, the internals of the Image andrelated classes will be postponed to later chapters. In this chapter,the focus will be on the basic mechanics of loading an image anddisplaying it.<P>The two forms of the <TT>getImage()</TT>method of the Applet class give you a simple way to load an image.Both these methods require an instance of a URL object. Althoughthe specifics of the URL class will be discussed in more detailshortly, it's enough to say here that the URL class is used toencapsulate a URL. Typically, the URL object used in the <TT>getImage()</TT>method will be, in part, generated by one of two Applet classmethods:<BR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -