📄 ch25.htm
字号:
public class MouseApplet extends Applet{ int coordX, coordY; public void init() { coordX = -1; coordY = -1; Font font = new Font("TimesRoman", Font.BOLD, 24); setFont(font); resize(400, 300); } public void paint(Graphics g) { if (coordX != -1) g.drawString("Click!", coordX, coordY); } public boolean mouseDown(Event evt, int x, int y) { coordX = x; coordY = y; 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>MouseApplet</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the class's data fields.<BR> Override the <TT>init()</TT> method.<BR> Initialize the click coordinates.<BR> Create and set the font for the applet.<BR> Size the applet.<BR> Override the <TT>paint()</TT> method.<BR> If the user has selected a coordinate...<BR> Draw the word Click! at the selected coordinate.<BR> Override the <TT>mouseDown()</TT> method.<BR> Save the mouse click's coordinates.<BR> Force Java to repaint the applet.<BR> Tell Java that the event was handled.<BR></BLOCKQUOTE><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>When you run MouseApplet, you'll discover that the applet window gets erased each time the <TT>paint()</TT> method is called. That's why only one "Click!" ever appears in the window.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="HandlingMouseMovement">Handling Mouse Movement</A></H3><P>Although mouse clicks are the most common type of mouse eventto which your applet may want to respond, tracking the mouse pointer'smovement can also be useful. Drawing programs, for example, enableyou to draw shapes by tracking the movement of the mouse and displayingthe results on the screen.<P>Unlike mouse clicks, though, which are rare, only occurring whenthe user presses a mouse button, <TT>MOUSE_MOVE</TT> events comeflooding into your applet by the hundreds as the user moves themouse around the screen. Each one of these events can be handledin the <TT>mouseMove()</TT> method, whose signature looks likethis:<BLOCKQUOTE><PRE>public boolean mouseMove(Event evt, int x, int y)</PRE></BLOCKQUOTE><P>Yep. Except for its name, the <TT>mouseMove()</TT> method looksexactly like the <TT>mouseDown()</TT> method, receiving as argumentsan <TT>Event</TT> object and the X,Y coordinates at which theevent occurred.<H3><A NAME="ExampleRespondingtoMouseMovementinanApplet">Example: Responding to Mouse Movement in an Applet</A></H3><P>Responding to mouse movement isn't something you have to do oftenin your applets. Still, it's a handy tool to have on your belt.You might, for example, need to track mouse movement when writinga game applet that uses the mouse as input. A more common useis in graphics programs that enable you to draw on the screen.Listing 25.2 is just such an applet.<P>When you run MouseApplet2 with Appletviewer, you see a blank window.Click the mouse in the window to choose a starting point and thenmove the mouse around the window. Wherever the mouse pointer goes,it leaves a black line behind (Figure 25.2). Although this isa very simple drawing program, it gives you some idea of how youmight use a mouse to accomplish other similar tasks.<P><A HREF="f25-2.gif"><B> Figure 25.2 : </B><I>This applet draws by tracking the movement of the mouse.</I></A><P><HR><BLOCKQUOTE><B>Listing 25.2 MouseApplet2.java: An Applet That TracksMouse Movement.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class MouseApplet2 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<numPoints; ++x) { g.drawLine(oldX, oldY, points[x].x, points[x].y); oldX = points[x].x; oldY = points[x].y; } } public boolean mouseDown(Event evt, int x, int y) { drawing = true; startPoint.x = x; startPoint.y = y; return true; } public boolean mouseMove(Event evt, int x, int y) { if ((drawing) && (numPoints < 1000)) { points[numPoints] = new Point(x, y); ++numPoints; 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>MouseApplet2</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the class's data fields.<BR> Override the <TT>init()</TT> method.<BR> Initialize the starting point.<BR> Create an array for storing the coordinates of line segments.<BR> Create and set the font for the applet.<BR> Set point count to zero.<BR> Set drawing flag off.<BR> Size the applet.<BR> Override the <TT>paint()</TT> method.<BR> Initialize the drawing's starting point.<BR> Cycle through each element in the <TT>points[]</TT> array.<BR> Draw a line segment.<BR> Save ending point as the starting point for the nextline.<BR> Override the <TT>mouseDown()</TT> method.<BR> Set the flag in order to allow drawing to begin.<BR> Save the mouse click's coordinates.<BR> Tell Java that the event was handled.<BR> Override the <TT>mouseMove()</TT> method.<BR> if it's okay to add another line segment...<BR> Create a new point and save the mouse's coordinates.<BR> Increment the point counter.<BR> Force Java to repaint the applet.<BR> Tell Java that the event was handled.</BLOCKQUOTE><H2><A NAME="TheKeyboard"><FONT SIZE=5 COLOR=#Ff0000>The Keyboard</FONT></A></H2><P>The keyboard has been around even longer than the mouse and hasbeen the primary interface between humans and their computersfor decades. Given the keyboard's importance, obviously theremay be times when you'll want to handle the keyboard events ata lower level than you can with something like a <TT>TextField</TT>control. Java responds to two basic key events, which are representedby the <TT>KEY_PRESS</TT> and <TT>KEY_RELEASE</TT> constants.As you'll soon see, Java defines methods that make it just aseasy to respond to the keyboard as it is to respond to the mouse.<H3><A NAME="RespondingtoKeyPresses">Responding to Key Presses</A></H3><P>Whenever the user presses a key when an applet is active, Javasends the applet a <TT>KEY_PRESS</TT> event. In your applet, youcan respond to this event by overriding the <TT>keyDown()</TT>method, whose signature looks like this:<BLOCKQUOTE><PRE>public boolean keyDown(Event evt, int key)</PRE></BLOCKQUOTE><P>As you can see, this method receives two arguments, which arean <TT>Event</TT> object and an integer representing the key thatwas pressed. This integer is actually the ASCII representationof the character represented by the key. In order to use thisvalue in your programs, however, you must first cast it to a <TT>char</TT>value, like this:<BLOCKQUOTE><PRE>char c = (char)key;</PRE></BLOCKQUOTE><H3><A NAME="PredefinedKeyConstants">Predefined Key Constants</A></H3><P>Some of the keys on your keyboard issue commands rather than generatecharacters. These keys include all the F keys, as well as keyslike Shift, Ctrl, Page Up, Page Down, and so on. In order to makethese types of keys easier to handle in your applets, Java's <TT>Event</TT>class defines a set of constants that represent these key's values.Table 25.2 lists these constants.<BR><P><CENTER><B>Table 25.2 Key Constants of the </B><I>Event</I><B>Class.</B></CENTER><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=145><I><B>Constant</B></I></TD><TD WIDTH=204><I><B>Key</B></I></TD></TR><TR VALIGN=TOP><TD WIDTH=145>DOWN</TD><TD WIDTH=204>The down arrow key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>END</TD><TD WIDTH=204>The End key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f1</TD><TD WIDTH=204>The f1 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f2</TD><TD WIDTH=204>The f2 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f3</TD><TD WIDTH=204>The f3 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f4</TD><TD WIDTH=204>The f4 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f5</TD><TD WIDTH=204>The f5 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f6</TD><TD WIDTH=204>The f6 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f7</TD><TD WIDTH=204>The f7 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f8</TD><TD WIDTH=204>The f8 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f9</TD><TD WIDTH=204>The f9 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f10</TD><TD WIDTH=204>The f10 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f11</TD><TD WIDTH=204>The f11 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>f12</TD><TD WIDTH=204>The f12 key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>HOME</TD><TD WIDTH=204>The Home key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>LEFT</TD><TD WIDTH=204>The left arrow key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>PGDN</TD><TD WIDTH=204>The Page Down key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>PGUP</TD><TD WIDTH=204>The Page Up key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>RIGHT</TD><TD WIDTH=204>The right arrow key.</TD></TR><TR VALIGN=TOP><TD WIDTH=145>UP</TD><TD WIDTH=204>The up arrow key.</TD></TR></TABLE></CENTER><P><H3><A NAME="KeyModifiers">Key Modifiers</A></H3><P>The <TT>Event</TT> class also defines a number of constants formodifier keys that the user might press along with the basic key.These constants include <TT>ALT_MASK</TT>, <TT>SHIFT_MASK</TT>,and <TT>CTRL_MASK</TT>, which represent the Alt, Shift, and Ctrl(or Control) keys on your keyboard. The <TT>SHIFT_MASK</TT> and<TT>CTRL_MASK</TT> constants are used in the <TT>Event</TT> class'smethods <TT>shiftDown()</TT> and <TT>controlDown()</TT>, eachwhich of returns a <TT>boolean</TT> value indicating whether themodifier key is pressed. (There currently is no <TT>altDown()</TT>method.) You can also examine the <TT>Event</TT> object's <TT>modifiers</TT>field to determine whether a particular modifier key was pressed.For example, if you wanted to check for the Alt key, you mightuse a line of Java code like this:<BLOCKQUOTE><PRE>boolean altPressed = (evt.modifiers & Event.ALT_MASK) != 0;</PRE></BLOCKQUOTE><P>By ANDing the mask with the value in the <TT>modifiers</TT> field,you end up with a non-zero value if the Alt key was pressed anda 0 if it wasn't. You convert this result to a <TT>boolean</TT>value by comparing the result with 0.<H3><A NAME="ExampleUsingKeyPressesinanApplet">Example: Using Key Presses in an Applet</A></H3><P>Although capturing key presses is a fairly simple process, there'snothing like an example applet to put the theoretical stuff tothe test. Listing 25.3 is an applet called KeyApplet that displays
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -