📄 ch28.htm
字号:
<BLOCKQUOTE>You can load ConnectApplet's HTML file using Appletviewer, if you like. However, you will be unable to make a connection to the requested URL. You can, however, see what happens when you enter a badly constructed URL string.</BLOCKQUOTE></TD></TR></TABLE></CENTER><HR><BLOCKQUOTE><B>Listing 28.3 ConnectApplet.java: An Applet ThatConnects to User-Requested URLs.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.net.*;public class ConnectApplet extends Applet{ TextField textField; boolean badURL; public void init() { textField = new TextField("", 40); Button button = new Button("Connect"); add(textField); add(button); badURL = false; } public void paint(Graphics g) { Font font = new Font("TimesRoman", Font.PLAIN, 24); g.setFont(font); int height = font.getSize(); if (badURL) g.drawString("Bad URL!", 60, 130); else { g.drawString("Type the URL to which", 25, 130); g.drawString("you want to connect,", 25, 130+height); g.drawString("and then click the Connect", 25, 130+height*2); g.drawString("button.", 25, 130 + height*3); } } public boolean action(Event evt, Object arg) { String str = textField.getText(); try { URL url = new URL(str); AppletContext context = getAppletContext(); context.showDocument(url); } catch (MalformedURLException e) { badURL = true; repaint(); } return true; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the applet uses the classes in the <TT>awt</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>applet</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>net</TT>package.<BR>Derive the <TT>ConnectApplet</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the class's data fields.<BR> Override the <TT>init()</TT> method.<BR> Create the <TT>TextField</TT> and <TT>Button</TT> controls.<BR> Add the controls to the applet's layout.<BR> Initialize the bad URL flag.<BR> Override the <TT>paint()</TT> method.<BR> Create and set the <TT>Graphics</TT> object's font.<BR> Get the font's height.<BR> If the applet has a bad URL string...<BR> Display an error message.<BR> Or, of the URL is OK...<BR> Draw the applet's instructions.<BR> Override the <TT>action()</TT> method.<BR> Get the URL string the user entered.<BR> Start the try block.<BR> Attempt to create an URL object from the string.<BR> Get the <TT>AppletContext</TT> object.<BR> Make the connection.<BR> Start the catch block.<BR> Set the bad URL flag to true.<BR> Repaint the applet in order to display the error message.<BR> Tell Java that the applet handled the event message.</BLOCKQUOTE><HR><BLOCKQUOTE><B>Listing 28.4 CONNECTAPPLET.htmL: ConnectApplet'sHTML Document.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE><title>Applet Test Page</title><h1>Applet Test Page</h1><applet code="ConnectApplet.class" width=300 height=250 name="ConnectApplet"></applet></PRE></BLOCKQUOTE><HR><H2><A NAME="CreatingaquotFavoriteURLsquotApplet"><FONT SIZE=5 COLOR=#Ff0000>Creating a "Favorite URLs" Applet</FONT></A></H2><P>Nothing, of course, says that the string from which you createan <TT>URL</TT> object must be typed in by the user at runtime.You can hard-code the URLs you want to use right in the applet'ssource code, which not only ensures that the URLs will alwaysbe correct (unless the associated server changes), but also makesit quick and easy to jump to whatever URL you want. Using thisidea, you can put together an applet that gives you pushbuttoncontrol over your connections, selecting your URLs as easily asyou'd select a radio station.<P>The ConnectApplet2 applet, shown in Listing 28.5, is just suchan applet. In its current version, it provides four buttons thatgive you instant connection to the Web sites represented by thebuttons. Want to jump to Microsoft's Web page? Give the Microsoftbutton a click. Want to check out the latest news at MacmillanComputer Publishing? Click the Macmillan button. Of course, justas with the original ConnectApplet, you must have your Internetconnection established before you run the applet. And, you mustrun the applet from a Java-compatible browser.<P>When you run the applet from Netscape Navigator 2.0, you see thewindow shown in Figure 28.4. As you can see, the applet currentlydisplays four buttons, one each for the Sun, Netscape, Microsoft,and Macmillan Web sites. Just click a button to jump to the associatedsite. (Figure 28.5 shows the browser after the user has clickedthe Macmillan button.) When you're through with that site, usethe browser's Back button to return to the ConnectApplet2 applet.Then, choose another site.<P><A HREF="f28-4.gif"><B> Figure 28.4 : </B><I>ConnectApplet2 running under Netscape Navigator 2.0.</I></A><P><P><A HREF="f28-5.gif"><B> Figure 28.5 : </B><I>After clicking the Macmillan button.</I></A><P><P>Sure, you can do the same sort of thing with an HTML documentusing Web links. But, let's face it, applets are way cooler.<HR><BLOCKQUOTE><B>Listing 28.5 ConnectApplet2.java: A "FavoriteURLs" Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.net.*;public class ConnectApplet2 extends Applet{ boolean badURL; public void init() { GridLayout layout = new GridLayout(2, 2, 10, 10); setLayout(layout); Font font = new Font("TimesRoman", Font.PLAIN, 24); setFont(font); Button button = new Button("Sun"); add(button); button = new Button("Netscape"); add(button); button = new Button("Microsoft"); add(button); button = new Button("Macmillan"); add(button); badURL = false; } public void paint(Graphics g) { if (badURL) g.drawString("Bad URL!", 60, 130); } public boolean action(Event evt, Object arg) { String str; if (arg == "Sun") str = "http://www.sun.com"; else if (arg == "Netscape") str = "http://www.netscape.com"; else if (arg == "Microsoft") str = "http://www.microsoft.com"; else str = "http://www.mcp.com"; try { URL url = new URL(str); AppletContext context = getAppletContext(); context.showDocument(url); } catch (MalformedURLException e) { badURL = true; repaint(); } return true; }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the applet uses the classes in the <TT>awt</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>applet</TT>package.<BR>Tell Java that the applet uses the classes in the <TT>net</TT>package.<BR>Derive the <TT>ConnectApplet2</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the class's data field.<BR> Override the <TT>init()</TT> method.<BR> Create and set the applet's layout manager.<BR> Create and set the applet's font.<BR> Add four button controls to the layout.<BR> Initialize the bad URL flag.<BR> Override the <TT>paint()</TT> method.<BR> If the applet has a bad URL string...<BR> Display an error message.<BR> Override the <TT>action()</TT> method.<BR> Declare a local string variable.<BR> Get the <TT>URL</TT> string the user requested.<BR> Start the try block.<BR> Create an <TT>URL</TT> object from the string.<BR> Get the <TT>AppletContext</TT> object.<BR> Make the connection.<BR> Start the catch block.<BR> Set the bad URL flag to true.<BR> Repaint the applet in order to display the error message.<BR> Tell Java that the applet handled the event message.</BLOCKQUOTE><P>In Listing 28.5, notice how, even though the URLs are hard-codedinto the program, the <TT>action()</TT> method still surroundsthe call to the <TT>URL</TT> constructor with the <TT>try</TT>and <TT>catch</TT> program blocks. This is because Java insiststhat the applet handle the exception should the <TT>URL</TT> classthrow it. If you remove the exception handling, the applet won'tcompile. Anyway, having a little extra protection never hurts.Handling the exception is a good way to test whether your hard-codedURLs are valid. I've never known a programmer yet who didn't needto be protected from himself!<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Although a running applet has to deal with many security considerations,it can usually connect to other Web sites. To do this, the appletcreates an <TT>URL</TT> object representing the site to whichthe applet should connect. The applet then instructs the browsercontaining the applet to make the connection, by calling the <TT>AppletContext</TT>object's <TT>showDocument()</TT> method. In spite of the telecommunicationslimitations inherent in applets, you can easily create Internet-awareapplets.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is the single argument accepted by the version of theURL constructor you studied in this chapter?<LI>What is an AppletContext object?<LI>How do you obtain a AppletContext object?<LI>How can you be sure you have a valid URL object before tryingto connect to the URL?<LI>What are the two types of program blocks that handle exceptions?<LI>How do you connect to the URL represented by an URL object?<LI>What type of exception is thrown by the <TT>URL</TT> class?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an applet that accepts<!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -