giáo trình Java By Example phần 8 ppt

46 395 0
giáo trình Java By Example phần 8 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Review Questions How do you use a try program block?1. How do you use a catch program block?2. Do you have to catch all types of exceptions that might be thrown by Java?3. When a method you call is defined as potentially throwing an exception, do you have to handle that exception in your program? 4. How many exceptions can you associate with a single try block?5. How do you pass an exception up from a called method to the calling method?6. What are the two main types of exceptions that Java may throw?7. Review Exercises Write an applet that creates a button object. Set up exception-handling code for the OutOfMemoryException exception that could possibly occur when Java tries to allocate resources for the button. 1. Write an applet that catches all Exception objects and displays the string returned by the Exception object's getMessage() method. (Not all Exception objects return message strings. Test your program by generating a divide-by-zero error, which will cause Java to throw an ArithmeticException exception. This exception does generate a message string.) You can find the solution to this exercise in the CHAP30 folder of this book's CD-ROM. The applet is called ExceptionApplet4. Figure 30.8 shows what the applet looks like while running under Appletviewer. Figure 30.8 : ExceptionApplet4 displays the message string returned by an Exception object's getMessage() method. 2. Write an applet that enables the user to enter values into an array. Use two TextField objects, the first being where the user shouldenter the index at which to place the value, and the second being the value to add to the array. Set up the applet so that it responds to ArrayIndexOutOfBoundsException and NumberFormatException exceptions. You can find the solution to this exercise in the CHAP30 folder of this book's CD-ROM. The applet is called ExceptionApplet5. Figure 30.9 shows what the applet looks like while running under Appletviewer. Figure 30.9 : This is ExceptionApplet5 running under Appletviewer. 3. http://www.ngohaianh.info Chapter 28 Communications CONTENTS URL Objects Example: Creating an URL Object❍ URL Exceptions❍ ● The Applet Context Example: Using an AppletContext to Link to an URL❍ Example: Using an AppletContext in an Applet❍ ● Creating a "Favorite URLs" Applet● Summary● Review Questions● Review Exercises● Not to state the obvious, but because applets are used on the Internet, they have the ability to perform a few types of telecommunications tasks. One of these tasks, connecting to other Web sites, is a snap to implement. Other tasks, such as accessing data in files, are difficult to implement because you constantly stumble over the security restrictions built into applets. Dealing with the intricacies of Internet security is beyond the scope of this book. If you're interested in this topic, you should pick up an advanced Java book. In this chapter, though, you'll get a chance to use Java to communicate over the Internet by connecting to URLs that the user supplies. URL Objects In the previous chapter, you got a quick introduction to URL objects when you obtained the location of graphics and sound files by calling the getDocumentBase() and getCodeBase() methods. You used the URL objects returned by these methods in order to display images and play sounds that were stored on your computer. In that case, the locations of the files were on your own system. What you didn't know then is that you can create an URL object directly by calling its constructor. Using this technique, you can create URL objects that represent other sites on the World Wide Web. Although the URL class's constructor has several forms, the easiest to use requires a string argument holding the URL from which you want to create the object. Using this constructor, you create the URL object like this: http://www.ngohaianh.info URL url = new URL(str); This constructor's single argument is the complete URL of the location to which you want to connect. This URL string must be properly constructed or the URL constructor will throw an exception (generate an error). You'll soon see what to do about such errors. Example: Creating an URL Object Suppose you want to create an URL object for the URL http://www.sun.com, which is where you can find lots of information about Java. You'd create the URL object like this: URL url = new URL("http://www.sun.com"); If the URL construction goes okay, you can then use the URL object however you need to in your applet. URL Exceptions As I mentioned previously, if the argument for the URL constructor is in error (meaning that it doesn't use valid URL syntax), the URL class throws an exception. Because the URL class is designed to throw an exception when necessary, Java gives you no choice except to handle that exception properly. This prevents the applet from accidentally attempting to use a defective URL object. You'll learn all the details about handling exceptions in Chapter 30, "Exceptions." For now, though, you need to know how to handle the URL exception because your applets will not compile properly until you add the exception-handling code. Basically, when you need to watch out for an exception, you enclose the code that may generate the error in a try program block. If the code in the block generates an exception, you handle that exception in a catch program block. (It's no coincidence that when code "throws" an exception, Java expects the program to "catch" that exception.) When you create an URL object from a string, you must watch out for the MalformedURLException exception, which is one of the many exceptions defined by Java. To do this, use the try and catch program blocks, as shown in Listing 28.1. Listing 28.1 LST28_1.TXT: Handling URL Exceptions. try { URL url = new URL(str); http://www.ngohaianh.info } catch (MalformedURLException e) { DisplayErrorMessage(); } The Applet Context Once you have the URL object created, you need a way to pass it on to the browser in which the applet is running. It is the browser, after all, that will make the Web connection for you. But, how do you refer to the browser from within your applet? You call the getAppletContext() method, which returns an AppletContext object. This AppletContext object represents the browser in which the applet is running. You call getAppletContext() like this: AppletContext context = getAppletContext(); Once you have the context, you can link to the URL represented by the URL object you already created. You do this by calling the AppletContext object's showDocument() method, like this: context.showDocument(url); If all goes well, the above line will connect you to the requested URL. Example: Using an AppletContext to Link to an URL Suppose that you want to enable the user to enter an URL string in your applet and then use URL and AppletContext objects to link to that URL. Listing 28.2 shows how you might accomplish this feat of Internet prestidigitation: Listing 28.2 LST28_2.TXT: Linking to an URL. String str = GetURLStringFromUser(); http://www.ngohaianh.info try { URL url = new URL(str); AppletContext context = getAppletContext(); context.showDocument(url); } catch (MalformedURLException e) { DisplayErrorMessage(); } In Listing 28.2, the program first calls a method that retrieves a text string from the user. This text string is the URL to which the user wants to connect. Then, the try program block starts. The first line inside the try block attempts to create an URL object from the string the user entered. Of course, because user's often make mistakes when typing in long strings of characters, the string the user entered may not be a syntactically valid URL. In that case, program execution automatically jumps to the catch program block, where your applet displays an appropriate error message. If the URL object gets created okay, though, the program finishes the code in the try block, getting the AppletContext object and making the link to the URL. In this case, Java completely ignores the catch block. Example: Using an AppletContext in an Applet Ready for a full-fledged example? Listing 28.3 is a complete applet that enables the user to link to an URL. Listing 28.4 is the HTML document that loads the applet. Because this applet actually interacts with a browser and the Internet, you must have made your Internet connection before running the applet. Then, to run the applet, load its HTML document into a Java-compatible browser such as Netscape Navigator 2.0. When you do, you'll see a window similar to that shown in Figure 28.1. In this figure, the user has already entered the URL he wishes to visit. In Figure 28.2, the browser has made the requested connection. Figure 28.3 shows the browser when the user enters an invalid URL string. Figure 28.1 : Here, the user is ready to make a connection. Figure 28.2 : If the URL is OK, the browser connects. Figure 28.3 : If the URL is constructed improperly, the applet displays an error message. http://www.ngohaianh.info NOTE 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. Listing 28.3 ConnectApplet.java: An Applet That Connects to User-Requested URLs. 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; http://www.ngohaianh.info } 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) http://www.ngohaianh.info { String str = textField.getText(); try { URL url = new URL(str); AppletContext context = getAppletContext(); context.showDocument(url); } catch (MalformedURLException e) { badURL = true; repaint(); } return true; } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Tell Java that the applet uses the classes in the net package. Derive the ConnectApplet class from Java's Applet class. Declare the class's data fields. Override the init() method. Create the TextField and Button controls. http://www.ngohaianh.info Add the controls to the applet's layout. Initialize the bad URL flag. Override the paint() method. Create and set the Graphics object's font. Get the font's height. If the applet has a bad URL string Display an error message. Or, of the URL is OK Draw the applet's instructions. Override the action() method. Get the URL string the user entered. Start the try block. Attempt to create an URL object from the string. Get the AppletContext object. Make the connection. Start the catch block. Set the bad URL flag to true. Repaint the applet in order to display the error message. Tell Java that the applet handled the event message. Listing 28.4 CONNECTAPPLET.htmL: ConnectApplet's HTML Document. <title>Applet Test Page</title> <h1>Applet Test Page</h1> <applet code="ConnectApplet.class" width=300 height=250 name="ConnectApplet"> </applet> http://www.ngohaianh.info Creating a "Favorite URLs" Applet Nothing, of course, says that the string from which you create an URL object must be typed in by the user at runtime. You can hard-code the URLs you want to use right in the applet's source code, which not only ensures that the URLs will always be correct (unless the associated server changes), but also makes it quick and easy to jump to whatever URL you want. Using this idea, you can put together an applet that gives you pushbutton control over your connections, selecting your URLs as easily as you'd select a radio station. The ConnectApplet2 applet, shown in Listing 28.5, is just such an applet. In its current version, it provides four buttons that give you instant connection to the Web sites represented by the buttons. Want to jump to Microsoft's Web page? Give the Microsoft button a click. Want to check out the latest news at Macmillan Computer Publishing? Click the Macmillan button. Of course, just as with the original ConnectApplet, you must have your Internet connection established before you run the applet. And, you must run the applet from a Java-compatible browser. When you run the applet from Netscape Navigator 2.0, you see the window shown in Figure 28.4. As you can see, the applet currently displays four buttons, one each for the Sun, Netscape, Microsoft, and Macmillan Web sites. Just click a button to jump to the associated site. (Figure 28.5 shows the browser after the user has clicked the Macmillan button.) When you're through with that site, use the browser's Back button to return to the ConnectApplet2 applet. Then, choose another site. Figure 28.4 : ConnectApplet2 running under Netscape Navigator 2.0. Figure 28.5 : After clicking the Macmillan button. Sure, you can do the same sort of thing with an HTML document using Web links. But, let's face it, applets are way cooler. Listing 28.5 ConnectApplet2.java: A "Favorite URLs" Applet. import java.awt.*; import java.applet.*; import java.net.*; public class ConnectApplet2 extends Applet { boolean badURL; http://www.ngohaianh.info [...]... referring to a Java class For example, to create a new button object, you could write java. awt.Button button = new java. awt.Button(label) As you can see, however, such program lines become unwieldy, which is why Java supports the import statement Creating Your Own Packages As you write your own classes, you're going to want to organize the related classes into packages just as Java does You do this by organizing... The preceding example is a complete interface, meaning that it can be compiled, after which other Java programs can reference it You compile an interface exactly the same way you compile a class First, you save the interface's source code in a file with the java extension Then you use the Java compiler, javac, to compile the source code into byte-code form Just like a normal class, the byte-code file... element being separated by a dot The use of the different names separated by the dots illustrates the hierarchy that Java' s creators used when they created the Java packages This hierarchy is used not only as a way of referring to class names in source code, but also as a way to organize the CLASS files that comprise a class library If you look in your JAVA\ LIB folder, you'll find the JAVA folder, within... enable you to play, stop, and loop the sound http://www.ngohaianh.info Review Questions 1 2 3 4 5 6 7 8 9 What two types of image files can be loaded by a Java applet? What two parameters are required by methods such as getImage() and getAudioClip()? What's the only type of audio file recognized by Java? How do you display an image after it's loaded? Do image and sound files always have to be stored... prompt, type javac DisplayClass .java Java's compiler then compiles the DisplayClass .java file, creating the DisplayClass.class file in your DISPLAY folder As you can see in Figure 29.2, if you now look in your DISPLAY folder, you'll have not only the original source code file for the DisplayClass class, but also the DisplayClass.class file, which is the class's byte-code representation that Java can understand... been using Java packages since the first applet you created That's because all of the Java Developer's Kit's classes are organized into packages You've been importing those packages into your source code with code similar to this: http://www.ngohaianh.info import java. awt.*; import java. applet.*; If you examine either of these lines, you'll see that each starts with the word java followed by a package... r Example: Using the New Package r q Creating Your Own Packages Example: Extending the Package Interfaces r The Basic Interface r Example: Creating an Interface r Implementing an Interface q Summary q Review Questions q Review Exercises As you write more and more Java source code, you're going to start having a hard time finding the snippets of code you need for your current project You may, for example, ... 3 Type javac PackageApplet .java to compile the applet into a class file 4 Run the applet by typing appletviewer packageapplet.html When you run the PackageApplet applet, you see the window shown in Figure 29.3 The text that's displayed in the applet is acquired by the call to the DisplayClass class's GetDisplayText() method This class is part of your new Display class When you run the applet, Java knows... same directory as the applet (This sound file is included with the Java Developer's Kit and has been copied to this chapter's CD-ROM directory for your convenience.) Figure 27.3 : Click the button to hear the applet's sound file Listing 27.2 SoundApplet .java: An Applet That Plays a Sound File import java. awt.*; import java. applet.*; import java. net.*; http://www.ngohaianh.info public class SoundApplet... exercise in the CHAP 28 folder of this book's CD-ROM.) Figure 28. 6 : The more Web-site buttons you add, the more places you can visit with a click of the mouse http://www.ngohaianh.info http://www.ngohaianh.info Chapter 27 Images and Sounds CONTENTS q Image Types q Loading and Displaying an Image r r Example: Using the getCodeBase() Method r Loading an Image r Displaying an Image r q Example: Using the . which is one of the many exceptions defined by Java. To do this, use the try and catch program blocks, as shown in Listing 28. 1. Listing 28. 1 LST 28_ 1.TXT: Handling URL Exceptions. try { URL. badly constructed URL string. Listing 28. 3 ConnectApplet .java: An Applet That Connects to User-Requested URLs. import java. awt.*; import java. applet.*; import java. net.*; public class ConnectApplet. face it, applets are way cooler. Listing 28. 5 ConnectApplet2 .java: A "Favorite URLs" Applet. import java. awt.*; import java. applet.*; import java. net.*; public class ConnectApplet2 extends

Ngày đăng: 22/07/2014, 16:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan