⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch27.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 2 页
字号:
that displays a small image using the techniques described previouslyin this chapter. When you run the applet with Appletviewer, yousee the window shown in Figure 27.1. Make sure the SNAKE.gif imageis in the same directory as the ImageApplet.class file, sincethat's where the program expects to find it.<P><A HREF="f27-1.gif"><B> Figure 27.1 : </B><I>This is ImageApplet running under Appletviewer.</I></A><P><HR><BLOCKQUOTE><B>Listing 27.1&nbsp;&nbsp;ImageApplet.java: An Applet That Displaysan Image.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.net.*;public class ImageApplet extends Applet{    Image snake;    public void init()    {        URL codeBase = getCodeBase();        snake = getImage(codeBase, &quot;snake.gif&quot;);        resize(250, 250);    }    public void paint(Graphics g)    {        int width = snake.getWidth(this);        int height = snake.getHeight(this);        g.drawRect(52, 52, width+10, height+10);        g.drawImage(snake, 57, 57, width, height, this);    }}</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 net package.<BR>Derive the <TT>ImageApplet</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare the class's image data field.<BR>    Override the <TT>init()</TT> method.<BR>        Retrieve the base URL.<BR>        Load the image.<BR>        Size the applet.<BR>    Override the <TT>paint()</TT> method.<BR>        Get the image's width and height.<BR>        Draw a framing rectangle for the image.<BR>        Draw the image within the rectangle.</BLOCKQUOTE><P>Notice how the applet imports the classes in the <TT>net</TT>package, which is where the <TT>URL</TT> class lives. If you failto include this line at the top of the program, Java will be unableto find the <TT>URL</TT> class and the applet will not compile.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>By using different values for the <TT>drawImage()</TT> method's width and height arguments, you can display an image at any size you like. For example, to display an image at twice its normal size, just use <TT>2*width</TT> and <TT>2*height</TT> for the width and height arguments. To display the image at half its normal size, use <TT>width/2</TT> and <TT>height/2</TT>. Figure 27.2 shows the snake image displayed at twice its normal size. It doesn't even fit in the window any more!</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P><A HREF="f27-2.gif"><B> Figure 27.2 : </B><I>Here's the snake image at twice its size.</I></A><P><H2><A NAME="PlayingaSound"><FONT SIZE=5 COLOR=#Ff0000>Playing a Sound</FONT></A></H2><P>Just as there are many types of image files, so too are theremany types of sound files. But, when it comes to applets, theonly type of sound file you need to know about are audio files,which have the file extension AU. These types of sound files werepopularized on UNIX machines and are the only type of sound fileJava can load and play.<P>When you want to play a sound from beginning to end, you onlyhave to call <TT>getDocumentBase()</TT> or <TT>getCodeBase()</TT>for the URL and then call <TT>play()</TT> to play the sound. Acall to <TT>play()</TT> looks like this:<BLOCKQUOTE><PRE>play(baseURL, relLocation);</PRE></BLOCKQUOTE><P>The <TT>play()</TT> method's two arguments are the URL returnedfrom a call to <TT>getDocumentBase()</TT> or <TT>getCodeBase()</TT>and the relative location of the sound file.<H3><A NAME="ExampleUsingtheIplayIMethod">Example: Using the <I>play()</I> Method</A></H3><P>Suppose you have your CLASS files in the directory C:/MYHOMEPAGEand your AU files in the directory C:/MYHOMEPAGE/AUDIO. The followinglines then will load and play an audio file called SOUND.AU:<BLOCKQUOTE><PRE>URL codeBase = getCodeBase();play(codeBase, &quot;audio/sound.au&quot;);</PRE></BLOCKQUOTE><H3><A NAME="ExamplePlayingaSoundinanApplet">Example: Playing a Sound in an Applet</A></H3><P>Now get ready to write an applet that plays a sound file. Listing27.2 is the applet in question, called SoundApplet. When you runthe applet with Appletviewer, you'll see the window shown in Figure27.3. Just click the button to hear the sound. Of course, youneed to have a sound card properly installed on your system. Youalso must be sure that the SPACEMUSIC.AU sound file is in thesame directory as the applet. (This sound file is included withthe Java Developer's Kit and has been copied to this chapter'sCD-ROM directory for your convenience.)<P><A HREF="f27-3.gif"><B> Figure 27.3 : </B><I>Click the button to hear the applet's sound file.</I></A><P><HR><BLOCKQUOTE><B>Listing 27.2&nbsp;&nbsp;SoundApplet.java: An Applet That Playsa Sound File.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.net.*;public class SoundApplet extends Applet{    Button button;    public void init()    {        BorderLayout layout = new BorderLayout();        setLayout(layout);        Font font = new Font(&quot;TimesRoman&quot;, Font.BOLD, 32);        setFont(font);        button = new Button(&quot;Play Sound&quot;);        add(&quot;Center&quot;, button);        resize(250, 250);    }    public boolean action(Event evt, Object arg)    {        if (evt.target instanceof Button)        {            URL codeBase = getCodeBase();            play(codeBase, &quot;spacemusic.au&quot;);        }        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>SoundApplet</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare the class's button object.<BR>    Override the <TT>init()</TT> method.<BR>        Create and set the applet's layout.<BR>        Create and set the applet's font.<BR>        Create and add the button.<BR>        Size the applet.<BR>    Override the <TT>action()</TT> method.<BR>        If the user clicks the button...<BR>            Get the base URL.<BR>            Play the sound.<BR>        Tell Java that the event was handled.</BLOCKQUOTE><H3><A NAME="ControllingSounds">Controlling Sounds</A></H3><P>Although the applet's <TT>play()</TT> method is the easiest wayto load and play sounds, it doesn't give you much control. Youhave only one option: play the sound from beginning to end. Ifyou want a little more control over your sounds, you can createan <TT>AudioClip</TT> object and use the object's methods to controlthe sound. Unfortunately, even the <TT>AudioClip</TT> class doesn'tgive you much power, although you can play, stop, and loop thesound.<P>To create the <TT>AudioClip</TT> object, you call the <TT>getAudioClip()</TT>method, like this:<BLOCKQUOTE><PRE>AudioClip audioClip = getAudioClip(baseURL, relLocation);</PRE></BLOCKQUOTE><P>This method's two arguments are the sound file's base URL andrelative location.<P>Once you have the <TT>AudioClip</TT> object created and loaded,you can call its methods to control the sound. There are onlythree from which to choose: <TT>play()</TT>, <TT>stop()</TT>,and <TT>loop()</TT>. The <TT>play()</TT> method plays the soundonce from beginning to end, <TT>stop()</TT> stops the sound whetheror not it has finished playing, and <TT>loop()</TT> causes thesound to keep repeating until it's stopped.<H3><A NAME="ExampleUsinganAudioClipinanApplet">Example: Using an AudioClip in an Applet</A></H3><P>Although using audio clips is a little more complicated than simplyloading and playing a sound using the applet's <TT>play()</TT>method, it's still a straightforward process. Listing 27.3 isan applet that creates an <TT>AudioClip</TT> object and enablesthe user to send commands to the object using the applet's commandbuttons. When you run the applet with Appletviewer, you see thewindow shown in Figure 27.4. To play the sound once from beginningto end, click the Play button. To stop the sound at any time,click the Stop button. Finally, to play the sound over and over,click the Loop button.<P><A HREF="f27-4.gif"><B> Figure 27.4 : </B><I>This is Appletviewer running SoundApplet2.</I></A><P><HR><BLOCKQUOTE><B>Listing 27.3&nbsp;&nbsp;SoundApplet2.java: An Applet That Createsand Displays an </B><I>AudioClip</I><B> Object.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.net.*;public class SoundApplet2 extends Applet{    AudioClip soundClip;    public void init()    {        GridLayout layout = new GridLayout(1, 3, 10, 10);        setLayout(layout);        Font font = new Font(&quot;TimesRoman&quot;, Font.BOLD, 24);        setFont(font);        Button button = new Button(&quot;Play&quot;);        add(button);        button = new Button(&quot;Stop&quot;);        add(button);        button = new Button(&quot;Loop&quot;);        add(button);        URL codeBase = getCodeBase();        soundClip = getAudioClip(codeBase, &quot;spacemusic.au&quot;);        resize(250, 250);    }    public boolean action(Event evt, Object arg)    {        if (arg == &quot;Play&quot;)            soundClip.play();        else if (arg == &quot;Stop&quot;)            soundClip.stop();        else if (arg == &quot;Loop&quot;)            soundClip.loop();        return true;    }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=<!-- 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 + -