Applets can handle both images and audio. As we write this, images must be in GIF, PNG, or JPEG form, audio files in AU, AIFF, WAV, or MIDI. Animated GIFs are supported, and the animation is displayed. Usually the files containing this information are specified as a URL, so we take up URLs first. Encapsulating URLsA URL is really nothing more than a description of a resource on the Internet. For example, "http://java.sun.com/index.html" tells the browser to use the hypertext transfer protocol on the file index.html located at java.sun.com. Java has the class URL that encapsulates URLs. The simplest way to make a URL is to give a string to the URL constructor: URL u = new URL("http://java.sun.com/index.html"); This is called an absolute URL because we specify the entire resource name. Another useful URL constructor is a relative URL. URL data = new URL(u, "data/planets.dat"); This specifies the file planets.dat, located in the data subdirectory of the URL u. A common way of obtaining a URL is to ask an applet where it came from, in particular:
To find the former, use the getdocumentBase method; to find the latter, use getCodeBase. NOTE
NOTE
Obtaining Multimedia FilesYou can retrieve images and audio files with the getImage and getAudioClip methods. For example: Image cat = getImage(getCodeBase(), "images/cat.gif"); AudioClip meow = getAudioClip(getCodeBase(), "audio/meow.au"); Here, we use the getCodeBase method that returns the URL from which your applet code is loaded. The second argument of the method calls specifies where the image or audio clip is located, relative to the base document. NOTE
You saw in Chapter 7 how to display an image. To play an audio clip, simply invoke its play method. You can also call the play method of the Applet class without first loading the audio clip. play(getCodeBase(), "audio/meow.au"); For faster downloading, multimedia objects can be stored in JAR files (see the section below). The getImage and getAudioClip/play methods automatically search the JAR files of the applet. If the image or audio file is contained in the JAR file, it is loaded immediately. Otherwise, the browser requests it from the web server. java.net.URL 1.0
java.applet.Applet 1.0
|