📄 ch6.htm
字号:
<P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=185><TT><B>getCodeBase()</FONT></B></TT></TD><TD WIDTH=406>Returns the URL of this Applet class (the one used to start the applet). This could be the value specified in the <APPLET> tag CODEBASE attribute or the directory of the HTML file in which this applet is embedded.</TD></TR><TR VALIGN=TOP><TD WIDTH=185><TT><B>GetDocumentBase()</FONT></B></TT></TD><TD WIDTH=406>Returns the URL of the HTML containing this applet.</TD></TR></TABLE></CENTER><P><P>Perhaps the <TT>getImage()</TT> methodyou will find the most useful is the one that takes two arguments:a base URL and a String representing the path or filename in relationto the base. In the example that follows, the image is loadedfrom a subdirectory off where the applet HTML is located:<BLOCKQUOTE><TT>Image img = getImage(getDocumentBase(),"images/mail.gif");</TT></BLOCKQUOTE><P>The other <TT>getImage()</TT> methodtakes a URL object as its only parameter. This will have the fullpath and filename of the image. The multiple constructors of URLobjects will be discussed shortly, but the construction of a URLobject with a String is illustrated as follows:<BLOCKQUOTE><TT>Image img = getImage(new URL("http://AFakeServer.com/images/mail.gif"));</TT></BLOCKQUOTE><P>Once you get the image, it is ready to be drawn. When the <TT>paint()</TT>method is invoked, an image is drawn by calling the <TT>drawImage()</TT>method of the Graphics object:<BLOCKQUOTE><TT>g.drawImage(img,10,10,this);</TT></BLOCKQUOTE><P>This code draws the Image created in the previous example at anx, y coordinate. The last <BR>parameter refers to an implementation of the ImageObserver interface.This class is used for tracking the progress of an image as itis loaded and decoded. This makes it possible to show partialimages as the full image is being constructed. The ImageObserverinterface will be discussed in more detail later, along with itsrelated classes and methods. For now, it's enough to say thatthe AWT Component class provides the basic methods necessary formanaging this image display behavior. The "this" ofthe above <TT>drawImage()</TT> samplecode refers to the component displaying the object.<P>Listing 6.5 and Figure 6.3 illustrate an applet that loads animage and displays it at different scales each time the appletreceives a mouse click. The image is loaded in the applet <TT>init()</TT>method by using <TT>getImage()</TT>.The first time the image appears, it is at its normal size usingthe version of <TT>drawImage()</TT>previously discussed. When you click the mouse, it changes theimage's scale and forces the applet to be redrawn. If the imageis not at its normal scale, then it's displayed at its modifiedsize with the following code:<P><A HREF="f6-3.gif" ><B>Figure 6.3 : </B><I>Drawing a scaled Applet image </I></A><BLOCKQUOTE><TT>int width = img.getWidth(this);<BR>int height = img.getHeight(this);<BR>g.drawImage(img,10,10,scale * width,scale * height,this);</TT></BLOCKQUOTE><P>The first two statements use methods of the Image class to getthe width and height of the image. A different version of the<TT>drawImage()</TT> method is usedto draw the image scaled to fit inside a bounding box specifiedby a width and height. The image is automatically scaled to fittightly inside the box. In the case of this example, the widthand height are multiplied by values of <TT>2</TT>,<TT>3</TT>, and <TT>4</TT>.<HR><BLOCKQUOTE><B>Listing 6.5. Code for drawing scaled images.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.applet.Applet;<BR><BR>public class TestImage extends Applet {<BR> // Load the image off the document base...<BR> Image img;<BR> int scale = 1;<BR> public final int MAX_SCALE = 4;<BR> public void init() {<BR> img = getImage(getDocumentBase(),"images/mail.gif");<BR>// Set toggle state...<BR> }<BR><BR> // Paint the image at its normal size or attwice<BR> // its normal size...<BR> public void paint(Graphics g) {<BR> // Show at normal scale<BR> if (scale == 1) {<BR> g.drawImage(img,10,10,this);<BR> }<BR> // Or make bigger...<BR> else {<BR> int width= img.getWidth(this);<BR> int height= img.getHeight(this);<BR> g.drawImage(img,10,10,scale* width,<BR> scale* height,this);<BR> }<BR> }<BR><BR> // Mouse clicks change the scale of the image<BR> public boolean mouseDown(Event ev, int x, inty) {<BR> ++scale;<BR> // If the max size of theimage is reached, then<BR> // go back to normal size...<BR> if (scale > MAX_SCALE)<BR> scale= 1;<BR> // Force a repaint of theimage...<BR> repaint();<BR> return true;<BR> };<BR>}<BR></TT></BLOCKQUOTE><HR><P>An interesting thing to note is that the Toolkit class providesits own versions of <TT>getImage()</TT>.One takes a single URL parameter as in the Applet single parameter<TT>getImage()</TT> method; this Toolkitmethod is used in this chapter's project. The other version of<TT>getImage()</TT> takes a singleString parameter that describes the file containing the image.<H2><A NAME="AppletsandAudio"><FONT SIZE=5 COLOR=#FF0000>Appletsand Audio</FONT></A></H2><P>The Applet class has two simple methods for loading and playingan audio clip. These <TT>play()</TT>methods have two variations, as the <TT>getImage()</TT>method does: One takes a fully constructed URL of the desiredaudio clip; the other method takes a base URL, plus a String specifyingadditional directory and filename information. For example, thefollowing code could be called to play a sound located off theHTML directory:<BLOCKQUOTE><TT>play(getDocumentBase(),"audio/song.au");</TT></BLOCKQUOTE><P>The only audio format currently supported by Java is the AU format,but this limitation will probably be relaxed in the near future.<P>Another way to play a sound is to create an AudioClip object.AudioClip is an interface implemented by the native environmentJava is running on. Just like <TT>play()</TT>and <TT>getImage()</TT>, the Appletclass offers two ways to get a reference to an AudioClip. TheApplet class <TT>getAudioClip()</TT>method with a single URL parameter is one way of getting a referenceto an AudioClip object:<BLOCKQUOTE><TT>import java.applet.AudioClip;<BR>// …<BR>AudioClip sound = getAudioClip(new URL("http://AFakeServer.com/audio/song.au"));</TT></BLOCKQUOTE><P>Note that the AudioClip interface is actually located in the Appletpackage. You can also refer to an AudioClip by giving a URL anda String representing additional directory and filename information.<P>Once you have an AudioClip, it can be played with the <TT>play()</TT>method. This method takes no parameters and plays the clip onlyonce. The <TT>loop()</TT> method playsthe sound repeatedly:<BLOCKQUOTE><TT>sound.loop();</TT></BLOCKQUOTE><P>The <TT>stop()</TT> method is usedto terminate the playing of the audio clip:<BLOCKQUOTE><TT>sound.stop();</TT></BLOCKQUOTE><P>It is important to remember to stop an audio clip when you leavethe page that started the clip. The <TT>stop()</TT>method of the applet should, therefore, call the AudioClip <TT>stop()</TT>when appropriate.<H2><A NAME="UndertheAppletHood"><FONT SIZE=5 COLOR=#FF0000>Underthe Applet Hood</FONT></A></H2><P>It is worth spending a few moments to look at the underpinningsof the Applet class. Closely related to the Applet class is theAppletContext interface, which represents the underlying appletenvironment. This will typically be a browser, such as NetscapeNavigator or HotJava. Therefore, the AppletContext provides alink to the resources of the browser. The Applet method <TT>getAppletContext()</TT>is used to return a reference to this underlying context.<P>Once you get access to the AppletContext object, it's possibleto do all kinds of interesting things. One of the simplest andmost useful things to do is to display a message on the browser'sstatus bar:<BLOCKQUOTE><TT>getAppletContext().showStatus("Thisis a message");</TT></BLOCKQUOTE><P>The various projects throughout this book use this technique todisplay problems to the user. An interesting thing to do is touse this to show the results of an exception:<BLOCKQUOTE><TT>try {<BR> // … do something<BR>}<BR>// If exception, then show detail message to status bar…<BR>catch (Exception e) {<BR> getAppletContext().showStatus(e.getMessage());<BR>}</TT></BLOCKQUOTE><P>Since <TT>getAppletContext()</TT>is a method of the Applet context, this code needs to be calledfrom within an Applet subclass. However, now that this has beenexplained, it needs to be pointed out that the Applet class hasits own <TT>showStatus()</TT> methodwith the same function. Therefore, the first code fragment couldjust as easily have been the following:<BLOCKQUOTE><TT>showStatus("This is a message");</TT></BLOCKQUOTE><P>Actually, this code does little more than call the underlyingAppletContext <TT>showStatus()</TT>method.<P>Another important thing that the AppletContext can do is returnreferences of Applets running on the current HTML page. The <TT>getApplet()</TT>method takes a String name of an Applet and returns a referenceto it. The <TT>getApplet()</TT> methodenumerates the applets on the current page. Both of these areuseful for inter-applet communication.<P>The AppletContext also ties in to one of the basic functions ofa browser-dynamically linking to another HTML page. This can bedone in one simple method call! The basic form of <TT>showDocument()</TT>takes a URL and makes it the current HTML of the browser. Thisimplies that the <TT>stop()</TT> methodof the current applet will be called, because its container pagewill no longer be current. This chapter's project will use <TT>showDocument()</TT>to link from one page to another. Here is a code fragment fromthe project:<BLOCKQUOTE><TT>try {<BR> URLu = new URL(URLBase,link);<BR> System.out.println("Shownew doc: " + u);<BR> a.getAppletContext().showDocument(u);<BR>}<BR>catch (MalformedURLException e) {<BR> a.showStatus("MalformedURL: " + link);<BR>}<BR>catch (Exception e) {<BR> a.showStatus("Unableto go to link: " + e);<BR>}</TT></BLOCKQUOTE><P>It creates a URL of the new page to be loaded and calls <TT>showDocument()</TT>to go to it. Note how the browser status bar is used to displayany errors.<P>An alternative form of <TT>showDocument()</TT>takes a second String parameter that specifies the target frameor window to place the loaded page. This is useful for browsersthat support framed pages. Note, however, that this method (likethe other AppletContext methods) might not do anything if thenative browser does not support the action.<P>Finally, a word should be said about the AppletStub interface.This interface is used to create a program to view applets. Consequently,any browser that supports Java will need to use the AppletStubinterface to make the Applet class functional.<H2><A NAME="CreatingandReadingaURL"><FONT SIZE=5 COLOR=#FF0000>Creatingand Reading a URL</FONT></A></H2><P>Since the Uniform Resource Locator, or URL, is at the heart ofthe World Wide Web, it is only appropriate that an Internet language
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -