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

📄 ch25.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<HTML><HEAD><TITLE>developer.com - Reference</TITLE><META NAME="Author" CONTENT="developer.com"><META NAME="Keywords" CONTENT="javascript, ActiveX, VRML, Push, channel,push channel, applet, directory, news, community, developer, internet,intranet, java, java applet, J++, javabeans, java products, tools, javatools, JDK, java development kit, java development environment, JIT,JavaPlan, enterprise tools, JVM, Java Virtual Machine, Java resources, API,browser, java documentation, CDF, Common Desktop Format, RDF, ResourceDescription Framework, Netcaster, Netcast, Castanet, meta-language, metadata,solaris, Solaris, SUN, CGI, Perl, Oracle, database, network, Netscape API,Apache, apache, SSL, mSQL, Netscape, Fasttrack, FastTrack,industry standard, ActiveX bridge, web, internet, site, sitedesign, microsoft, active server pages, asp, iis, nt, win95, 95, html, cgi,frontpage, business, corporate, vbscript, javascript, activex, isapi,database, access, sql, server, www, 3.0, 3.01, 3.02, 3.03, 3.04, 4.0,4.0b2, 4.01, 4.03, 4.04, connection, online, commerce, publisher,publishing, publish, webmaster, dynamic html, dhtml, windows 98, netscape,netscape software, shareware, magazines, jobs, japan, free, freeware, freestuff"><META NAME="description" CONTENT="Developer.com is the leading onlineservice for developers. It includes Gamelan, the official directory for Java, as wellas news, information, tutorials, and directories for other Internet technologiesincluding ActiveX, JavaScript, perl, VRML, Java Beans, push technologies, andother Internet and intranet technologies. Developer.com is also the home ofDeveloper Direct, the Professional Developer's Store, where developers canpurchase and download thousands of Web, authoring and other developmentproducts at some of today's lowest prices."><META NAME="distribution" CONTENT="global"><META NAME="resource-type" CONTENT="document"><META NAME="language" CONTENT="en"></HEAD><BODY BACKGROUND="/images/curve_r-wide.gif" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#DD0000" VLINK="#999999" ALINK="#FF0000"><TABLE><TR><TD VALIGN=TOP WIDTH=120><A HREF="/" ><IMG SRC="/images/masthead_r.gif" WIDTH="100" HEIGHT="78" BORDER="0"ALT="Developer.com Logo"></a></TD><TD><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCBAN.REF/DT=null"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCBAN.REF/DT=null" HEIGHT="60" WIDTH="468" ALT="Click here to support our advertisers"><BR><CENTER>Click here to support our advertisers</CENTER></a></TD></TR></TABLE><!--outer table--><TABLE><!--outer table--><TR><!--outer table--><TD VALIGN="TOP"><!--navbar info --><table><tr><td><A HREF="http://www.developerdirect.com/" ><IMG SRC="/images/button_s.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>SHOPPING</b></font></a></td></tr><tr><td><A HREF="/community/jobs/c_jobs.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>JOB BANK</B></font></a></td></tr><tr><td><A HREF="http://www.classifieds2000.com/cgi-cls/display.exe?Developer+computer+searchcomputercategories"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>CLASSIFIEDS</B></font></a></td></tr><tr><td><A HREF="/directories/directories.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>DIRECTORIES</B></font></a></td></tr><tr><td><A HREF="/reference/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>REFERENCE</B></font></a><br><a href="/reference/r_library.html"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">Online Library</a></font></td></tr><tr><td><A HREF="/classroom/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>LEARNING CENTER</B></font></a></td></tr><tr><td><A HREF="/journal/"><IMG SRC="/images/button_n.gif" width="15" height="11" BORDER="0"><B><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">JOURNAL</font></B></a></td></tr><tr><td><A HREF="/news/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>NEWS CENTRAL</b></font></a></td></tr><tr><td><A HREF="/downloads/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>DOWNLOADS</b></font></a></td></tr><tr><td><A HREF="/community/" ><IMG SRC="/images/button_c.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>COMMUNITY</B></font></a></td></tr><tr><td><A HREF="/calendar/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>CALENDAR</b></font></a></td></tr><tr><td><A HREF="/about/"><IMG SRC="/images/button_a.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>ABOUT US</b></a></font></td></tr></table><table><tr><td><form action="/subscribe/list.cgi" method=post ><img src="/images/rule.gif" width="100" height="2"><br><B><FONT FACE="Arial, Helvetica" SIZE="-1">Journal:</b></font><br><input name='email' value='your e-mail' size="11"><input type='hidden'  name='state' value='Subscribe'></td></tr><tr><td><input type='submit' value='Subscribe'><br><font size="-1">Get the weekly email highlights from the most popular journal for developers!<br><a href="http://www.developer.com/subscribe.html">Current issue</a><img src="/images/rule.gif" width="100" height="2"><input type='hidden' name='name' value='New Subscriber'></FORM></td></tr></table><!--/navbar--><font size="-1"><A HREF="http://www.developer.com">developer.com</a><BR><A HREF="http://www.developerdirect.com">developerdirect.com</a><BR><A HREF="http://www.htmlgoodies.com">htmlgoodies.com</a><BR><A HREF="http://www.javagoodies.com">javagoodies.com</a><br><A HREF="http://www.jars.com">jars.com</a><BR><a href="http://www.intranetjournal.com">intranetjournal.com</a><br><a href="http://www.javascripts.com">javascripts.com</a><br></font><!--outer table--></TD><!--outer table--><TD VALIGN="TOP"><BLOCKQUOTE><P><img src="/images/header_r.gif" width="440" height="50"><P><MAP NAME ="header_r2.gif.map"><AREA SHAPE ="RECT"      HREF ="/reference/author.html"      COORDS ="361,0,440,29"><AREA SHAPE ="RECT"      HREF ="/reference/basic.html"      COORDS ="254,0,360,29"><AREA SHAPE ="RECT"      HREF ="/reference/help.html"      COORDS ="183,0,251,29"><AREA SHAPE ="RECT"      HREF ="/reference/cool.html"      COORDS ="100,0,181,29"><AREA SHAPE ="RECT"      HREF ="/reference/mybook.html"      COORDS ="0,0,100,29"></MAP><MAP NAME ="header_r1.gif.map"><AREA SHAPE ="RECT"      HREF ="/reference/personalize.html"      COORDS ="339,0,439,29"></MAP><p><font face="Arial,Helvetica" size="-1" color="#006666"><A HREF="/reference/r_library.html"><B>All Categories</A> :</B><b><A HREF="/reference/r_java.html">Java</A></b></font><p><META><H1><FONT SIZE=6 COLOR=#Ff0000>Chapter&nbsp;25</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Mouse and Keyboard Events</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#TheEventObject">The Event Object</A><LI><A HREF="#TheMouse">The Mouse</A><UL><LI><A HREF="#HandlingMouseClicks">Handling Mouse Clicks</A><LI><A HREF="#ExampleUsingMouseClicksinanApplet">Example: Using Mouse Clicks in an Applet</A><LI><A HREF="#HandlingMouseMovement">Handling Mouse Movement</A><LI><A HREF="#ExampleRespondingtoMouseMovementinanApplet">Example: Responding to Mouse Movement in an Applet</A></UL><LI><A HREF="#TheKeyboard">The Keyboard</A><UL><LI><A HREF="#RespondingtoKeyPresses">Responding to Key Presses</A><LI><A HREF="#PredefinedKeyConstants">Predefined Key Constants</A><LI><A HREF="#KeyModifiers">Key Modifiers</A><LI><A HREF="#ExampleUsingKeyPressesinanApplet">Example: Using Key Presses in an Applet</A></UL><LI><A HREF="#HandlingEventsDirectly">Handling Events Directly</A><UL><LI><A HREF="#ExampleOverridingIhandleEventIinanApplet">Example: Overriding <I>handleEvent()</I> in an Applet</A></UL><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>Up until now, your applets have responded to events generatedby Java components like buttons, text fields, and list boxes.You've yet to examine how to respond to events generated by themost basic of a computer's controls, the mouse and the keyboard.Because virtually every computer has these important hardwarecontrols, you can confidently take advantage of them in your appletsto collect various types of input. In this chapter, you learnthe secrets of mouse and keyboard handling in Java applets.<H2><A NAME="TheEventObject"><FONT SIZE=5 COLOR=#Ff0000>The Event Object</FONT></A></H2><P>In order to understand how to respond to various types of events,you need to know more about Java's <TT>Event</TT> class, an objectof which is passed to any event-handling method. When you wantto respond to a Java button control, for example, you overridethe <TT>action()</TT> method, whose first argument is an <TT>Event</TT>object. You then examine the <TT>target</TT> field of the <TT>Event</TT>object to determine whether it was the button control that generatedthe event. The <TT>Event</TT> class, however, defines many constantsand data fields that provide information about the event representedby the object.<P>First, the <TT>Event</TT> class defines constants for all of theevents to which an event-handling method can respond. In thischapter, you'll learn about some of these constants, which include<TT>MOUSE_DOWN</TT>, <TT>MOUSE_UP</TT>, and <TT>KEY_PRESS</TT>.The class also defines constants for special keys, such as <TT>f1</TT>,<TT>PGUP</TT>, <TT>PGDN</TT>, <TT>HOME</TT>, and so on. Finally,the <TT>Event</TT> class defines the data fields shown in Table25.1. How you use these data fields depends on the type of eventrepresented by the <TT>Event</TT> object.<BR><P><CENTER><B>Table 25.1&nbsp;&nbsp;Data Fields of the </B><I>Event</I><B>Class.</B></CENTER><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=157><I><B>Field</B></I></TD><TD WIDTH=434><I><B>Description</B></I></TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>Object arg</TT></TD><TD WIDTH=434>Event-specific information. With a button event, for example, this field is the button's label.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int clickCount</TT></TD><TD WIDTH=434>The click count for mouse events. A value of 1 means a single click, and 2 means a double-click.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int id</TT></TD><TD WIDTH=434>The event's type, such as <TT>MOUSE_DOWN</TT>, <TT>MOUSE_MOVE</TT>, <TT>KEY_PRESS</TT>, etc.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int key</TT></TD><TD WIDTH=434>The key for a key-related event. For a <TT>KEY_PRESS</TT> event, for example, this would be the key that was pressed.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int modifiers</TT></TD><TD WIDTH=434>The key modifiers, including the shift and control keys. The <TT>Event</TT> class defines constants such as <TT>SHIFT_MASK</TT> and <TT>CTRL_MASK</TT>.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>Object target</TT></TD><TD WIDTH=434>The type of object-such as Button, TextField, and so on-that generated the event.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>long when</TT></TD><TD WIDTH=434>The event's time stamp.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int x</TT></TD><TD WIDTH=434>The X coordinate associated with the event, usually used with mouse events to indicate the mouse's position at the time of the event.</TD></TR><TR VALIGN=TOP><TD WIDTH=157><TT>int y</TT></TD><TD WIDTH=434>The Y coordinate associated with the event, usually used with mouse events to indicate the mouse's position at the time of the event.</TD></TR></TABLE></CENTER><H2><A NAME="TheMouse"><FONT SIZE=5 COLOR=#Ff0000>The Mouse</FONT></A></H2><P>Most people use their computer's mouse darn near as much as itskeyboard. I can vouch for this from first-hand experience, becausemy only bout with RSI (repetitive strain injury) came not fromtyping furiously all day, but from maneuvering my mouse to markparagraphs, highlight words, click buttons, make list selections,bring up menus, and any number of other mousely tasks. I'm notlooking for your sympathy, though. My point is that the mouseis one of the most important input devices attached to your computer.To write complete applets, you're going to have to master respondingto mouse events in your Java programs.<P>Luckily, responding to mouse input is a simple matter. Becauseresponding to the events generated by the mouse are such an importantand common task in modern programming, Java's classes alreadyinclude special methods for responding to these events. Exactlywhat events are you expected to handle? A mouse generates sixtypes of event messages that you can capture in your applets.These events are listed below, along with their descriptions andthe method that handles them:<UL><LI><TT>MOUSE_DOWN</TT>-This event, which is handled by the <TT>mouseDown()</TT>method, is caused when the user presses the mouse button.<LI><TT>MOUSE_UP</TT>-This event, which is handled by the <TT>mouseUp()</TT>method, is caused when the user releases the left mouse button.<LI><TT>MOUSE_MOVE</TT>-This event, which is handled by the <TT>mouseMove()</TT>method, occurs when the user moves the mouse pointer on the screen.<LI><TT>MOUSE_DRAG</TT>-This event, which is handled by the <TT>mouseDrag()</TT>method, is generated when the user moves the mouse pointer whileholding down the left mouse button.<LI><TT>MOUSE_ENTER</TT>-This event, which is handled by the <TT>mouseEnter()</TT>method, is sent when the mouse pointer enters the area owned byan applet or component.<LI><TT>MOUSE_EXIT</TT>-This event, which is handled by the <TT>mouseExit()</TT>method, occurs when the mouse pointer leaves the area owned byan applet or a component.</UL><P>In the sections that follow, you'll learn more about the mostcommonly used of these mouse events.<H3><A NAME="HandlingMouseClicks">Handling Mouse Clicks</A></H3><P>Without a doubt, the most commonly used mouse event in Java programs(and any other program written for a graphical user interface)is the <TT>MOUSE_DOWN</TT> event, which is generated wheneverthe user clicks within an applet. It's the <TT>MOUSE_DOWN</TT>event, for example, that lets Java know when an on-screen buttoncomponent has been clicked. You don't have to worry about clickson on-screen buttons (usually), because they're handled by Java.However, you can respond to <TT>MOUSE_DOWN</TT> events in yourapplets in order to accomplish other input tasks.<P>Java provides a couple of methods by which you can respond tomouse events. The easiest way to capture a <TT>MOUSE_DOWN</TT>event is to override the applet's <TT>mouseDown()</TT> method.Java automatically calls <TT>mouseDown()</TT> whenever the <TT>MOUSE_DOWN</TT>event is generated, which makes responding to this event easierthan melting butter with a blowtorch. The <TT>mouseDown()</TT>method's signature looks like this:<BLOCKQUOTE><PRE>public boolean mouseDown(Event evt, int x, int y)</PRE></BLOCKQUOTE><P>The arguments passed to the function are an <TT>Event</TT> objectand the X,Y coordinates of the mouse event. Although Java hasalready extracted the X,Y mouse coordinates for you, you can alsoget them from the <TT>Event</TT> object by examining the valuesstored in the <TT>x</TT> and <TT>y</TT> data fields, as describedin Table 25.1. (Because Java has already extracted the coordinatesfor you, though, it makes more sense to use the <TT>x</TT> and<TT>y</TT> parameters sent to the function.) What you do withthese coordinates depends, of course, on your applet. In the nextsection, you'll see how to use the coordinates to display graphicson the screen.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Although most of Java's event-handling methods automatically receive as arguments the basic information you need about a specific event (such as the coordinates of a mouse click), you can extract whatever additional information you need from the <TT>Event</TT> object, which is always the first parameter in a message-handling method.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="ExampleUsingMouseClicksinanApplet">Example: Using Mouse Clicks in an Applet</A></H3><P>As I was describing the <TT>mouseDown()</TT> method in the previoussection, I felt an example coming on. And, sure enough, here itis. The applet in Listing 25.1 responds to mouse clicks by printingthe word &quot;Click!&quot; wherever the user clicks in the applet.It does this by storing the coordinates of the mouse click inthe applet's <TT>coordX</TT> and <TT>coordY</TT> data fields.The <TT>paint()</TT> method then uses these coordinates to displaythe word. Figure 25.1 shows MouseApplet running under Appletviewer.<P><A HREF="f25-1.gif"><B> Figure 25.1 : </B><I>The MouseApplet applet responds to mouse clicks.</I></A><P><HR><BLOCKQUOTE><B>Listing 25.1&nbsp;&nbsp;MouseApplet.java: Using Mouse Clicksin an Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -