📄 ch6.htm
字号:
like Java has a URL class. Several examples of how to create anduse a URL object have already been presented in this chapter.There are four different constructors of URL objects. Two of themshould already be familiar. The simplest constructor takes a stringand converts it to a URL:<BLOCKQUOTE><TT>URL u = new URL("http://AFakeServer.com/");</TT></BLOCKQUOTE><P>Another method should also be familiar. It takes a URL and a Stringrepresenting a relative path and creates a new URL from it.<BLOCKQUOTE><TT>URL urlNew = new URL(u,"audio/sound.au");</TT></BLOCKQUOTE><P>Recall that a URL typically consists of a protocol, the name ofthe host computer, and a path to the location of the resource.A third URL constructor takes these as protocol, host, and fileStrings, respectively, and returns a URL. The final constructoradds a String specifying the port as an additional parameter.However, protocols generally have a fixed port number (HTTP is80), so this information is usually not needed.<P>A couple of methods can be used for deconstructing a URL. Thefollowing code prints the protocol, host, port, file, and finallythe URL itself of the HTML of the applet:<BLOCKQUOTE><TT>System.out.println("Protocol: "+ getDocumentBase().getProtocol());<BR>System.out.println("Host: " + getDocumentBase().getHost());<BR>System.out.println("Port: " + getDocumentBase().getPort());<BR>System.out.println("File: " + getDocumentBase().getFile());<BR>System.out.println("URL: " + getDocumentBase());</TT></BLOCKQUOTE><P>Once constructed, the URL can be used to open up a network connectionto the URL. This is done through the <TT>openStream()</TT>method, which returns an instance of InputStream. You saw howInputStream classes worked in <A HREF="ch4.htm" >Chapter 4</A>,"Enhancing the Spreadsheet Applet." The FilterInputStreamsubclasses can be constructed from this to create high-level interfacesto the streams. The DataInputStream class can be used to readin streams according to a specified data type, such as Strings.Listing 6.6 shows how to combine the URL and stream classes fora quick and easy printout of the contents of the HTML containingan applet.<HR><BLOCKQUOTE><B>Listing 6.6. Printing the contents of the applet's HTML.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>void printSelf() {<BR> // Open up a stream to the document URLand<BR> // print its contents...<BR> try {<BR> DataInputStreamdis = new DataInputStream(<BR> newBufferedInputStream(<BR> getDocumentBase().openStream()) );<BR> String s;<BR> while ( (s = dis.readLine())!= null)<BR> System.out.println(s);<BR> System.out.println("EOF");<BR> }<BR> catch (IOException e) {<BR> System.out.println("URLread error");<BR> }<BR> }</TT></BLOCKQUOTE><HR><P>The key to this is the first line in the <TT>try</TT>clause. The URL of the base document is taken from <TT>getDocumentBase()</TT>;its <TT>OpenStream()</TT> method isthen applied. Once the stream is open, an instance of the easy-to-useDataInputStream class is created. Each line of the HTML is thenfetched by the <TT>readLine()</TT>method of DataInputStream and sent to standard output.<H2><A NAME="ChapterProject"><FONT SIZE=5 COLOR=#FF0000>ChapterProject</FONT></A></H2><P>This chapter's project begins the development of a kiosk-styleonline catalog. It has a couple of interesting characteristics.First of all, it uses HTML applet parameters to describe how eachapplet is constructed and operates. Each page in the catalog hasimages describing the current choices. Figure 6.4 shows the mainmenu of the catalog. The images are loaded and displayed by theapplet, not the HTML. When a choice is made, the applet jumpsto the next HTML and reloads the applet with the new parameters.<P><A HREF="f6-4.gif" ><B>Figure 6.4 : </B><I>Main menu of the online catalog </I></A><P>Since the applet makes extensive use of images, it poses certainproblems. Images use much network bandwidth and so need to beused efficiently. The project works around this problem by creatinga MediaLoader class that acts as a cache for images. In the nextchapter, this class is improved by acting as a pre-loader of imagesbefore the next applet is retrieved.<P>Another notable feature of the project is its configurability.The same applet runs on every page of the catalog; its featuresare determined by <APPLET> tag parameters in the currentHTML. Furthermore, it uses a URL stream to load in additionaldata to be displayed on the button. This data comes from a localtext file, which can be edited outside the actual applet code.<H3><A NAME="ClassOrganization">Class Organization</A></H3><P>Table 6.1 lists the classes used in this chapter's version ofthe catalog applet.<BR><P><CENTER><B>Table 6.1. Catalog project classes.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=154><I>Class</I></TD><TD WIDTH=436><I>Description</I></TD></TR><TR VALIGN=TOP><TD WIDTH=154>CacheEntry</TD><TD WIDTH=436>Represents a single entry in the image cache maintained by the MediaLoader class.</TD></TR><TR VALIGN=TOP><TD WIDTH=154>Catalog</TD><TD WIDTH=436>The Applet class that takes HTML parameters and constructs the components that represent the current choices.</TD></TR><TR VALIGN=TOP><TD WIDTH=154>CatalogButton</TD><TD WIDTH=436>A image-based button that shows text representing a choice and links to another Catalog applet when selected.</TD></TR><TR VALIGN=TOP><TD WIDTH=154>MediaLoader</TD><TD WIDTH=436>A class that actually loads the images and uses static methods to employ a cache that exists across Catalog applet invocations.</TD></TR><TR VALIGN=TOP><TD WIDTH=154>MediaLoaderException</TD><TD WIDTH=436>An exception thrown by the MediaLoader when there is a problem.</TD></TR><TR VALIGN=TOP><TD WIDTH=154>SelectionCanvas</TD><TD WIDTH=436>Displays a large image representing a possible choice of the user. Appears to the right of its companion CatalogButton.</TD></TR></TABLE></CENTER><H3><A NAME="CatalogHTML">Catalog HTML</A></H3><P>Listing 6.7 shows the HTML of the catalog page displayed in Figure6.4. As the listing shows, the HTML does not actually displayanything. The <PARAM> tag fields actually tell the appletwhat to display. These are passed to the Catalog applet run foreach page of the applet. It reads in the parameters to determinewhat images to display. There are three rows of display for eachCatalog applet. On each row there is a field (also known as aCatalogButton, after its class) that appears on the left-handside; it is effectively a button that appears as an image. Thefield is complemented by a larger image that appears on its right(called a SelectionCanvas, after its class).<P>The three <PARAM> tagsý whose NAME attribute beginswith the "field" prefix specify the left-hand imagebuttons. The corresponding VALUE attribute has four subfieldsused to create the CatalogButton. The first subfield is the nameappearing on the button. The second is the image to be displayedin the button's area. The third subfield is a style, which representsthe size of the button. Although the MEDIUM style is the onlyone used in the sample applets, its existence gives you a wayof customizing the applet. The last subfield specifies the URLthat the applet goes to when you click the image button.<P>The three <PARAM> tags whose NAME attribute begins withthe "image" prefix specify the SelectionCanvas objectsthat appear to the right of the fields. The VALUE attribute specifiesthe image to be displayed in the canvas area.<P>The <PARAM> tag with the NAME attribute of "data"specifies a URL containing text data that can be used to complementthe display of the CatalogButton objects. This data would be suchthings as "On Sale" that would appear underneath thelarger font name of the button.<HR><BLOCKQUOTE><B>Listing 6.7. The HTML of the main catalog page (index.html).<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT><title>Catalog Applet</title><BR><hr><BR><applet code="Catalog" width=400 height=300><BR><param name=field1 value="Computers,catalog/field1.gif,MEDIUM,computer/main.html"><BR><param name=image1 value="catalog/selection1.gif"><BR><param name=field2 value="Software,catalog/field1.gif,MEDIUM,software/main.html"><BR><param name=image2 value="catalog/selection1.gif"><BR><param name=field3 value="Accessories,catalog/field1.gif,MEDIUM,accessory/</TT><FONT FACE="ZapfDingbats">Â</FONT><TT>main.html"><BR><param name=image3 value="catalog/selection1.gif"><BR><param name=data value="catalog/data.txt"><BR></applet><BR><hr></TT></BLOCKQUOTE><HR><H3><A NAME="TheCatalogClass">The Catalog Class</A></H3><P>Listing 6.7 gives the full listing of the Catalog class. Thissubclass of Applet represents the applet loaded for every pagein the catalog project. The initialization of the applet has threesteps. Its main job is to create the CatalogButton and SelectionCanvasobjects by parsing out the parameters specified in the currentHTML. However, it also traps for a mouse click on one of the CanvasButtonobjects in <TT>handleEvent()</TT>.When this occurs, it calls the CanvasButton <TT>select()</TT>method, which may result in the browser loading in a new URL representinga new page in the catalog.<P>After the Catalog applet initializes the fonts, it gets the appletparameter in the HTML that corresponds to the "data"NAME attribute. It does this through the <TT>getParameter()</TT>method, which will return either a String representation of thecorresponding VALUE attribute, or a null value if the name cannotbe found. The <TT>getParameter()</TT>method is used to get all the CatalogButton and SelectionCanvasparameters that follow.<P>After the "data" value is retrieved, it is used to derivea URL that contains the additional text data. This is performedin the applet's <TT>loadURLData()</TT>method. It creates a URL object by taking the path to the textdata in relation to the base document of the current HTML:<BLOCKQUOTE><TT>u = new URL(getDocumentBase(),dataPath);</TT>></TT></BLOCKQUOTE><P>It uses this URL object to open up an input stream to the textfile, then reads the data in by Strings delimited by newlines.This process is similar to the example discussed in the "Creatingand Reading a URL" section above.<P>The last step in the applet's initialization is to create thethree rows of CatalogButton and SelectionCanvas couplets. It usesthe <TT>getParameter()</TT> methodto get the information needed to create the canvas components.In the <TT>createCatalogButton()</TT>method, the parameter values are parsed with an instance of theStringTokenizer class. Given a set of delimiters (like commas),this class simply walks through and produces String tokens thatappear between the delimiters.<P>The other thing that the Catalog class does is handle the paintingof the applet. This is simple because it walks through the threerows and displays the components based on the size of their images.<HR><BLOCKQUOTE><B>Listing 6.7. The Catalog class.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.util.StringTokenizer;<BR>import java.applet.*;<BR>import java.net.URL;<BR>import java.io.DataInputStream;<BR>import java.io.BufferedInputStream;<BR>import java.io.IOException;<BR>import java.net.MalformedURLException;<BR><BR>// This is the main class that loads the parameters<BR>// for the current applet and sets up the images<BR>// fields.<BR>public class Catalog extends Applet {<BR> CatalogButton button[] = new CatalogButton[3];<BR> SelectionCanvas drawing[] = new SelectionCanvas[3];<BR> // Three styles<BR> private static final int SMALL_STYLE = 0;<BR> private static final int MEDIUM_STYLE = 1;<BR> private static final int LARGE_STYLE = 2;<BR> private static final int DEFAULT_STYLE = MEDIUM_STYLE;<BR> Font styleFont[] = new Font[3];<BR> Font dataFont;<BR> String data[] = new String[3];<BR><BR> // Initialize the graphic display...<BR> public void init() {<BR> // First create fonts...<BR> styleFont[0] = new Font("Helvetica",Font.PLAIN,16);<BR> styleFont[1] = new Font("Helvetica",Font.BOLD,18);<BR> styleFont[2] = new Font("Helvetica",Font.BOLD,24);<BR> dataFont = new Font("TimesRoman",Font.ITALIC,14);<BR> // Get the additional datafrom URL...<BR> loadURLData();<BR><BR> // Add the components...<BR> addComponents();<BR> show();<BR> }<BR><BR> // Add the components to the display...<BR> void addComponents() {<BR> // Create Font for buttons
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -