1. Trang chủ
  2. » Công Nghệ Thông Tin

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

46 400 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Java By Example Part 8 ppt
Trường học University of Science and Technology of Hanoi
Chuyên ngành Computer Science
Thể loại PPT
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 46
Dung lượng 111,84 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

{ String str = textField.getText; try { URL url = new URLstr; AppletContext context = getAppletContext; Tell Java that the applet uses the classes in the awt package.. Tell Java that

Trang 1

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 messagestrings Test your program by generating a divide-by-zero error, which will cause Java to throw anArithmeticException exception This exception does generate a message string.) You canfind the solution to this exercise in the CHAP30 folder of this book's CD-ROM The applet iscalled ExceptionApplet4 Figure 30.8 shows what the applet looks like while running under

ArrayIndexOutOfBoundsException and NumberFormatException exceptions Youcan find the solution to this exercise in the CHAP30 folder of this book's CD-ROM The applet iscalled ExceptionApplet5 Figure 30.9 shows what the applet looks like while running under

Appletviewer

Figure 30.9 : This is ExceptionApplet5 running under Appletviewer.

3

Trang 2

The Applet Context

Example: Using an AppletContext to Link to an URL

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 ofgraphics and sound files by calling the getDocumentBase() and getCodeBase() methods Youused the URL objects returned by these methods in order to display images and play sounds that werestored on your computer In that case, the locations of the files were on your own system What youdidn'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 argumentholding the URL from which you want to create the object Using this constructor, you create the URLobject like this:

Trang 3

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 youcan 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 usevalid URL syntax), the URL class throws an exception Because the URL class is designed to throw anexception 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 detailsabout 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 acatch 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 forthe 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);

Trang 4

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 isrunning It is the browser, after all, that will make the Web connection for you But, how do you refer tothe browser from within your applet? You call the getAppletContext() method, which returns anAppletContext object This AppletContext object represents the browser in which the applet isrunning 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 andAppletContext 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();

Trang 5

{

URL url = new URL(str);

AppletContext context = getAppletContext();

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 insidethe 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 createdokay, though, the program finishes the code in the try block, getting the AppletContext object andmaking 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 anURL Listing 28.4 is the HTML document that loads the applet Because this applet actually interactswith 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, theuser has already entered the URL he wishes to visit In Figure 28.2, the browser has made the requestedconnection 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.

Trang 6

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.

textField = new TextField("", 40);

Button button = new Button("Connect");

add(textField);

add(button);

badURL = false;

Trang 7

g.drawString("Type the URL to which", 25, 130);

g.drawString("you want to connect,",

Trang 8

{

String str = textField.getText();

try

{

URL url = new URL(str);

AppletContext context = getAppletContext();

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

Trang 9

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>

Trang 10

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 onlyensures that the URLs will always be correct (unless the associated server changes), but also makes itquick and easy to jump to whatever URL you want Using this idea, you can put together an applet thatgives you pushbutton control over your connections, selecting your URLs as easily as you'd select a radiostation

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 atMacmillan 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, youmust 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 Asyou can see, the applet currently displays four buttons, one each for the Sun, Netscape, Microsoft, andMacmillan Web sites Just click a button to jump to the associated site (Figure 28.5 shows the browserafter the user has clicked the Macmillan button.) When you're through with that site, use the browser'sBack 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.

Trang 11

public void init()

Trang 12

URL url = new URL(str);

AppletContext context = getAppletContext();

context.showDocument(url);

}

Trang 13

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 ConnectApplet2 class from Java's Applet class

Declare the class's data field

Override the init() method

Create and set the applet's layout manager

Create and set the applet's font

Add four button controls to the layout

Initialize the bad URL flag

Override the paint() method

If the applet has a bad URL string

Display an error message

Override the action() method

Declare a local string variable

Get the URL string the user requested

Start the try block

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

In Listing 28.5, notice how, even though the URLs are hard-coded into the program, the action()

Trang 14

method still surrounds the call to the URL constructor with the try and catch program blocks This isbecause Java insists that the applet handle the exception should the URL class throw it If you remove theexception handling, the applet won't compile Anyway, having a little extra protection never hurts.

Handling the exception is a good way to test whether your hard-coded URLs are valid I've never known

a programmer yet who didn't need to be protected from himself!

Summary

Although a running applet has to deal with many security considerations, it can usually connect to otherWeb sites To do this, the applet creates an URL object representing the site to which the applet shouldconnect The applet then instructs the browser containing the applet to make the connection, by callingthe AppletContext object's showDocument() method In spite of the telecommunications

limitations inherent in applets, you can easily create Internet-aware applets

2

Figure 28.6 : The more Web-site buttons you add, the more places you can visit with a click of the

mouse.

Trang 16

Loading and Displaying an Image

Example: Using the getDocumentBase() Method

no direct support for handling these types of files Even the Windows API, as immense as it is, provideslittle help when it comes to handling these graphical and aural chores Java, on the other hand, was

designed to make creating applets as easy as possible For that reason, Java's classes handle almost all thedifficulties associated with displaying images (commonly called bitmaps) and playing sounds In thischapter, you use Java's power to add images and sounds to your applets

Image Types

In the world of computers, there are many types of images, each of which is associated with a specificfile format These image types are usually identified by their file extensions, which include PCX, BMP,

Trang 17

GIF, JPEG (or JPG), TIFF (or TIF), TGA, and more Each of these file types was created by third-partysoftware companies for use with their products, but many became popular enough to grow into standards.The PCX graphics file type, for example, began as the format for PC Paintbrush files, whereas BMP filesare usually associated with the Windows graphical interface.

If you were writing your Internet applications using a more conventional language like C++, you couldchoose to support whatever image type was most convenient for your use This is because you'd have towrite all the file-loading code from scratch, anyway Java, on the other hand, comes complete with

classes that are capable of loading image files for you This convenience comes with a small price,

however, since Java can load only GIF and JPEG image file formats In this book, you'll use GIF files,which are more common, although JPEG files are rapidly gaining a reputation, especially for

high-resolution, true-color images

Loading and Displaying an Image

The first step in displaying an image in your applet is to load the image from disk To do this, you mustcreate an object of Java's Image class This is fairly easy to do; however, in order to do so, you need tocreate an URL object that holds the location of the graphics file You could just type the image's URLdirectly into your Java source code If you do this, however, you have to change and recompile the appletwhenever you move the graphics file to a different directory on your disk A better way to create theimage's URL object is to call either the getDocumentBase() or getCodeBase() method Theformer returns the URL of the directory from which the current HTML file was loaded, whereas the latterreturns the URL of the directory from which the applet was run

Example: Using the getDocumentBase() Method

As I said previously, the getDocumentBase() method returns the URL of the directory from whichthe HTML document was loaded If you're storing your images in the same directory (or a subdirectory

of that directory) as your HTML files, you'd want to use this method to obtain an URL for an image.Suppose you have your HTML documents in a directory called PUBLIC and the image you want, calledIMAGE.gif, is stored in a subdirectory of PUBLIC called IMAGES A call to getDocumentBase()will get you the appropriate base URL That call looks like this:

URL url = getDocumentBase();

As you'll soon see, once you have the URL, you can load the file by using the URL along with the

relative location of the image, which in this case would be IMAGES/IMAGE.gif The full URL to thefile would then be FILE:/C:/PUBLIC/IMAGES/IMAGE.gif If you decided to move your public files to adirectory called MYHOMEPAGE, the call to getDocumentBase() will give you the URL for thatnew directory, without your having to change the applet's source code This new URL, once you includedthe relative location of the image file, would be FILE:/C:/MYHOMEPAGE/IMAGES/IMAGE.gif

Trang 18

Example: Using the getCodeBase() Method

The getCodeBase() method works similarly to getDocumentBase(), except that it returns theURL of the directory from which the applet was loaded If you're storing your images in the same

directory (or a subdirectory of that directory) as your CLASS files, you'd want to call getCodeBase()

to obtain an URL for an image

Suppose you have your CLASS files in a directory called CLASSES and the image you want (still calledIMAGE.gif) is stored in a subdirectory of CLASSES called IMAGES A call to getCodeBase() willget you the base URL you need to load the image That call looks like this:

URL url = getCodeBase();

Again, once you have the URL, you can load the file by using the URL along with the relative location ofthe image, which would still be IMAGES/IMAGE.gif The full URL to the file would then be

FILE:/C:/CLASSES/IMAGES/IMAGE.gif

Loading an Image

Once you have the image's base URL, you're ready to load the image and create the Image object Youcan complete both of these tasks at the same time, by calling your applet's getImage() method, likethis:

Image image = getImage(baseURL, relLocation);

The getImage() method's two arguments are the URL returned by your call to getCodeBase() orgetDocumentBase() and the relative location of the image For example, assuming that you've

stored your CLASS files in the directory C:\CLASSES and your images in the directory

C:\CLASSES\IMAGES, you'd have a code that looks something like this:

URL codeBase = getCodeBase();

Image myImage = getImage(codeBase, "images/myimage.gif");

After Java has executed the above lines, your image is loaded into the computer's memory and ready todisplay

Trang 19

Displaying an Image

Displaying the image is a simple matter of calling the Graphics object's drawImage() method, likethis:

g.drawImage(myImage, x, y, width, height, this);

This method's arguments are the image object to display, the X and Y coordinates at which to display theimage, the width and height of the image, and the applet's this reference

TIP

When you want to display an image with its normal width and height,you can call a simpler version of the drawImage() method, whichleaves out the width and height arguments, like this:

drawImage(image, x, y, this) This version of the methodactually draws the image faster because it doesn't have to worry aboutreducing or expanding the image to the given width and height It justblasts it on to the screen exactly as the image normally appears

You may be wondering where you can get the width and the height of the image As it turns out (nodoubt thanks to careful consideration by Java's programmers over hundreds of cups of coffee), the

Image class has two methods, getWidth() and getHeight(), that return the width and height ofthe image The complete code for displaying the image, then, might look like this:

int width = image.getWidth(this);

int height = image.getHeight(this);

g.drawImage(image, x, y, width, height, this);

As you can see, the getWidth() and getHeight() methods require a single argument, which is theapplet's this reference

Example: Displaying an Image in an Applet

You're now ready to write an applet that can display images Listing 27.1 is the Java source code for anapplet called ImageApplet that displays a small image using the techniques described previously in thischapter When you run the applet with Appletviewer, you see the window shown in Figure 27.1 Makesure the SNAKE.gif image is in the same directory as the ImageApplet.class file, since that's where theprogram expects to find it

Figure 27.1 : This is ImageApplet running under Appletviewer.

Trang 20

Listing 27.1 ImageApplet.java: An Applet That Displays an Image.

URL codeBase = getCodeBase();

snake = getImage(codeBase, "snake.gif");

int width = snake.getWidth(this);

int height = snake.getHeight(this);

Trang 21

g.drawRect(52, 52, width+10, height+10);

g.drawImage(snake, 57, 57, width, height, this);

}

}

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 ImageApplet class from Java's Applet class

Declare the class's image data field

Override the init() method

Retrieve the base URL

Load the image

Size the applet

Override the paint() method

Get the image's width and height

Draw a framing rectangle for the image

Draw the image within the rectangle

Notice how the applet imports the classes in the net package, which is where the URL class lives If youfail to include this line at the top of the program, Java will be unable to find the URL class and the appletwill not compile

TIP

By using different values for the drawImage() method's width andheight arguments, you can display an image at any size you like Forexample, to display an image at twice its normal size, just use

2*width and 2*height for the width and height arguments Todisplay the image at half its normal size, use width/2 and

height/2 Figure 27.2 shows the snake image displayed at twice itsnormal size It doesn't even fit in the window any more!

Figure 27.2 : Here's the snake image at twice its size.

Playing a Sound

Just as there are many types of image files, so too are there many types of sound files But, when it

comes to applets, the only type of sound file you need to know about are audio files, which have the fileextension AU These types of sound files were popularized on UNIX machines and are the only type of

Trang 22

sound file Java can load and play.

When you want to play a sound from beginning to end, you only have to call getDocumentBase() orgetCodeBase() for the URL and then call play() to play the sound A call to play() looks likethis:

play(baseURL, relLocation);

The play() method's two arguments are the URL returned from a call to getDocumentBase() orgetCodeBase() and the relative location of the sound file

Example: Using the play() Method

Suppose you have your CLASS files in the directory C:/MYHOMEPAGE and your AU files in the

directory C:/MYHOMEPAGE/AUDIO The following lines then will load and play an audio file calledSOUND.AU:

URL codeBase = getCodeBase();

play(codeBase, "audio/sound.au");

Example: Playing a Sound in an Applet

Now get ready to write an applet that plays a sound file Listing 27.2 is the applet in question, calledSoundApplet When you run the applet with Appletviewer, you'll see the window shown in Figure 27.3.Just click the button to hear the sound Of course, you need to have a sound card properly installed onyour system You also must be sure that the SPACEMUSIC.AU sound file is in the same directory as theapplet (This sound file is included with the Java Developer's Kit and has been copied to this chapter'sCD-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.*;

Trang 23

public class SoundApplet extends Applet

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

TỪ KHÓA LIÊN QUAN