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

📄 ch25.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
whatever key the user presses. Figure 25.3 shows the applet runningunder Appletviewer.<P><A HREF="f25-3.gif"><B> Figure 25.3 : </B><I>This applet displays the last character typed.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>If you run KeyApplet under a browser like Netscape Navigator, click on the applet with your mouse before you start typing. This ensures that the applet has the focus and will receive the key presses.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><HR><BLOCKQUOTE><B>Listing 25.3&nbsp;&nbsp;KeyApplet.java: An Applet That CapturesKey Presses.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class KeyApplet extends Applet{    int keyPressed;    public void init()    {        keyPressed = -1;        Font font =            new Font(&quot;TimesRoman&quot;, Font.BOLD, 144);        setFont(font);        resize(200, 200);    }    public void paint(Graphics g)    {        String str = &quot;&quot;;        if (keyPressed != -1)        {            str += (char)keyPressed;            g.drawString(str, 40, 150);        }    }    public boolean keyDown(Event evt, int key)    {        keyPressed = key;        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>Derive the <TT>KeyApplet</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare the class's data field.<BR>    Override the <TT>init()</TT> method.<BR>        Initialize <TT>keyPressed</TT> to indicate no valid keyreceived yet.<BR>        Create and set the font for the applet.<BR>        Size the applet.<BR>    Override the <TT>paint()</TT> method.<BR>        Create the empty display string.<BR>        Draw the character on the screen.<BR>    Override the <TT>keyDown()</TT> method.<BR>        Save the key that was pressed.<BR>        Force Java to redraw the applet.<BR>        Tell Java that the event was handled.</BLOCKQUOTE><H2><A NAME="HandlingEventsDirectly"><FONT SIZE=5 COLOR=#Ff0000>Handling Events Directly</FONT></A></H2><P>All of the events received by your applet are processed by the<TT>handleEvent()</TT> method, which the <TT>Applet</TT> classinherits from the <TT>Component</TT> class. When this method isnot overridden in your applet, the default implementation is responsiblefor calling the many methods that respond to events. Listing 25.4shows how the <TT>handleEvent()</TT> method is implemented inthe <TT>Component</TT> class. By examining this listing, you caneasily see why you only have to override methods like <TT>mouseDown()</TT>to respond to events. In the next section, you see how to customize<TT>handleEvent()</TT> in your own programs.<HR><BLOCKQUOTE><B>Listing 25.4&nbsp;&nbsp;LST25_4.TXT: The Default Implementationof </B><I>handleEvent(&nbsp;)</I><B>.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>public boolean handleEvent(Event evt) {switch (evt.id) {  case Event.MOUSE_ENTER:    return mouseEnter(evt, evt.x, evt.y);  case Event.MOUSE_EXIT:    return mouseExit(evt, evt.x, evt.y);  case Event.MOUSE_MOVE:    return mouseMove(evt, evt.x, evt.y);  case Event.MOUSE_DOWN:    return mouseDown(evt, evt.x, evt.y);  case Event.MOUSE_DRAG:    return mouseDrag(evt, evt.x, evt.y);  case Event.MOUSE_UP:    return mouseUp(evt, evt.x, evt.y);  case Event.KEY_PRESS:  case Event.KEY_ACTION:    return keyDown(evt, evt.key);  case Event.KEY_RELEASE:  case Event.KEY_ACTION_RELEASE:    return keyUp(evt, evt.key);      case Event.ACTION_EVENT:    return action(evt, evt.arg);  case Event.GOT_FOCUS:    return gotFocus(evt, evt.arg);  case Event.LOST_FOCUS:    return lostFocus(evt, evt.arg);}return false;}</PRE></BLOCKQUOTE><HR><H3><A NAME="ExampleOverridingIhandleEventIinanApplet">Example: Overriding <I>handleEvent()</I> in an Applet</A></H3><P>Although the default implementation of <TT>handleEvent()</TT>calls special methods that you can override in your applet foreach event, you might want to group all your event handling inone method to conserve on overhead, change the way an applet respondsto a particular event, or even create your own events. To accomplishany of these tasks (or any others you might come up with), youcan forget the individual event-handling methods and override<TT>handleEvent()</TT> instead.<P>In your version of <TT>handleEvent()</TT>, you must examine the<TT>Event</TT> object's <TT>id</TT> field in order to determinewhich event is being processed. You can just ignore events inwhich you're not interested. However, be sure to return <TT>false</TT>whenever you ignore a message, so that Java knows that it shouldpass the event on up the object hierarchy. Listing 25.5 is a rewrittenversion of the MouseApplet2 applet, called MouseApplet3. Thisversion overrides the <TT>handleEvent()</TT> method in order torespond to events.<HR><BLOCKQUOTE><B>Listing 25.5&nbsp;&nbsp;MouseApplet3.java: Using the </B><I>handleEvent(&nbsp;)</I><B>Method.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class MouseApplet3 extends Applet{    Point startPoint;    Point points[];    int numPoints;    boolean drawing;    public void init()    {        startPoint = new Point(0, 0);        points = new Point[1000];        numPoints = 0;        drawing = false;        resize(400, 300);    }    public void paint(Graphics g)    {        int oldX = startPoint.x;        int oldY = startPoint.y;        for (int x=0; x&lt;numPoints; ++x)        {            g.drawLine(oldX, oldY, points[x].x, points[x].y);            oldX = points[x].x;            oldY = points[x].y;        }    }    public boolean handleEvent(Event evt)    {        switch(evt.id)        {            case Event.MOUSE_DOWN:                drawing = true;                startPoint.x = evt.x;                startPoint.y = evt.y;                return true;            case Event.MOUSE_MOVE:                if ((drawing) &amp;&amp; (numPoints &lt; 1000))                {                    points[numPoints] = new Point(evt.x, evt.y);                    ++numPoints;                    repaint();                }                return true;            default:                return false;        }    }}</PRE></BLOCKQUOTE><HR><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Because the keyboard and the mouse are two of the most importantdevices for accepting input from the user, it's important thatyou know how to handle these devices in your applets. Maybe mostof your applets will work fine by leaving such details up to Javaor maybe you'll want to have more control over the devices thanthe default behavior allows. You can capture most messages receivedby a Java applet by overloading the appropriate event handlers,such as <TT>mouseDown()</TT> and <TT>keyDown()</TT>. However,if you want to step back even further in your event-handling code,you can override the <TT>handleEvent()</TT> method, which receivesall events sent to an applet.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is the mouse event that's most commonly captured andresponded to in Java applets?<LI>What is the mouse message an applet receives the most of?<LI>What are the six different mouse event messages that yourapplet may receive?<LI>What are the two keyboard events your applet is likely toreceive?<LI>How can you determine what type of object generated an event?<LI>How can you determine the type of event message that's beingreceived?<LI>When your applet receives a mouse-related message, how canyou determine the coordinates of the mouse at the time of theevent?<LI>How can you tell whether the user single- or double-clickedhis mouse?<LI>What two methods are associated with the <TT>KEY_PRESS</TT>and <TT>KEY_RELEASE</TT> event messages?<LI>What arguments are received by the <TT>keyDown()</TT> method?<LI>What arguments are received by the <TT>mouseDown()</TT> method?<LI>Why might you need to use the <TT>SHIFT_MASK</TT> and <TT>CTRL_MASK</TT>constants?<LI>If you want to handle all events in a single method, whatmethod should you override in your applet?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an applet that displays a rectangle wherever the userclicks.<LI>Write an applet that displays a rectangle, the color whichchanges whenever the user presses a key on his keyboard.<LI>Write an applet that displays the current coordinates of themouse as the mouse moves around the applet's window.<LI>Write an applet that enables the user to type a string ofcharacters on the screen. Use a <TT>String</TT> object to holdthe characters, adding each new character to the string as theuser types and displaying the string in the applet's <TT>paint()</TT>method.<LI>Modify MouseApplet2 so that the first <TT>MOUSE_DOWN</TT>event selects a starting point, after which the applet remembersall the <TT>MOUSE_MOVE</TT> coordinates. However, the applet shouldn'tdraw the lines associated with these moves until the user presseshis f2 key. Pressing f3 should erase the lines from the appletand signal the applet to start the process over again. (You canfind the solution to this exercise, called MouseApplet4,  in theCHAP25 folder of this book's CD-ROM.)</OL><HR><HR WIDTH="100%"></P></CENTER><!-- 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 + -