📄 keylistener.html
字号:
implement a mouse listener that calls the <code>requestFocusInWindow</code> method when the component is clicked.</ol><blockquote><hr><strong>Version note:</strong> This page reflects the focus API introduced in released 1.4.As of that release, the focus subsystem consumes focus traversalkeys, such as Tab and Shift Tab. If you need to prevent the focustraversal keys from being consumed, you can call<blockquote><pre>component.setFocusTraversalKeysEnabled(false)</pre></blockquote>on the component that is firing the key events. Your programmust then handle focus traversal on its own. Alternatively,you can use a <code>KeyEventDispatcher</code> to pre-listento all key events. The <a class="TutorialLink" target="_top" href="../misc/focus.html">focus page</a> has detailed information on the focus subsystem.<hr></blockquote>You can obtain detailed information about aparticular key-pressed event.For example, you can query a key-pressed event todetermine if it was fired from an action key. Examples of action keysinclude Copy, Paste, Page Up, Undo, and the arrow and function keys.As of release 1.4,you can also query a key-pressed or key-released event to determinethe location of the key that fired the event. Most key events are fired fromthe standard keyboard, but the events for some keys, such asShift, have information on whether the user pressed the Shift key onthe left or the right side of the keyboard. Likewise, the number'2' can be typed from either the standard keyboard or from the number pad.<p>For key-typed events you can get the key character value as wellas any modifiers used.<blockquote><hr><strong>Note:</strong> You shouldn't rely on the key character value returnedfrom <code>getKeyChar</code> unless it's involved in akey-typed event.<hr></blockquote><p>The following example demonstrates key events.It consists of a text field that you can type into,followed by a text area that displays a message every time the text field fires a key event. A button at the bottom of the window lets you clear both the text field and text area.<p><p><center><IMG SRC="../../figures/uiswing/events/KeyEventDemo.png" WIDTH="383" HEIGHT="251" ALIGN="BOTTOM" ALT=""></center></p><p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/events/examples/KeyEventDemo.jnlp">Run KeyEventDemo</a> using <a href=http://java.sun.com/products/javawebstart> Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#KeyEventDemo">example index</a>.<li> Type a lowercase 'a' by pressing and releasing the A key on the keyboard. <br> The text field fires three events: a key-pressed event, a key-typed event, and a key-released event. Note that the key-typed event doesn't have key code information, and key-pressed and key-released events don't have key character information. None of the events so far are from modifier or action keys and the key location, reported on the key-pressed and key-released events, is most likely standard.<li> Press the Clear button. <br>You might want to do this after each of the following steps.<li> Press and release the Shift key. <br> The text field fires two events: a key pressed and a key released. The text field doesn't fire a key-typed event because Shift, by itself, doesn't correspond to any character.<li> Type an uppercase 'A' by pressing the Shift and A keys. <br> You'll see the following events, although perhaps not in this order: key pressed (Shift), key pressed (A), key typed ('A'), key released (A), key released (Shift). Note that Shift is listed as the modifier key for the key-typed and key-pressed events.<li> Type an uppercase 'A' by pressing and releasing the Caps Lock key, and then pressing the A key. <br> You should see the following events: key pressed (Caps Lock), key pressed (A), key typed ('A'), key released (A). Note that Caps Lock is <em>not</em> listed as a modifier key.<li> Press the Tab key. No Tab key-pressed or key-released events are received by the key event listener. This is because the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. Press Tab twice more to return the focus to the text area.<li> Press a function key, such as F3. You'll see that the function key is an action key.<li> Press the left Shift key, followed by the right Shift key. The key-pressed and key-released events indicate which Shift key was typed.<li> Press the Num Lock key if your keyboard has a number pad. <br> As for Caps Lock, there is a key-pressed event, but no key-released event.<li> Press the '2' key on the number pad. You see the key-pressed, key-typed, and key-released events for the number '2'.<li> Press the '2' key on the standard keyboard. Again, you see the three event messages. The key-typed events for both number 2 keys are identical. But the key-pressed and key-released events indicate different key codes and different key locations.<li> Press the Num Lock key again. A key-released event is fired.</ol><hr></blockquote><p>You can find the example's code in <a class="SourceLink" target="_blank" href="examples/KeyEventDemo.java"><code>KeyEventDemo.java</code></a>.Here is the demo's key event handling code:<blockquote><pre>public class KeyEventDemo ... implements KeyListener ... { <em>...//where initialization occurs:</em> typingArea = new JTextField(20); typingArea.addKeyListener(this); //Uncomment this if you wish to turn off focus //traversal. The focus subsystem consumes //focus traversal keys, such as Tab and Shift Tab. //If you uncomment the following line of code, this //disables focus traversal and the Tab events //become available to the key event listener. //typingArea.setFocusTraversalKeysEnabled(false); ... /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { displayInfo(e, "KEY TYPED: "); } /** Handle the key pressed event from the text field. */ public void keyPressed(KeyEvent e) { displayInfo(e, "KEY PRESSED: "); } /** Handle the key released event from the text field. */ public void keyReleased(KeyEvent e) { displayInfo(e, "KEY RELEASED: "); } ... protected void displayInfo(KeyEvent e, String s){ ... //You should only rely on the key char if the event //is a key typed event. int id = e.getID(); if (id == KeyEvent.KEY_TYPED) { char c = e.getKeyChar(); keyString = "key character = '" + c + "'"; } else { int keyCode = e.getKeyCode(); keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")"; } int modifiers = e.getModifiersEx(); modString = "modifiers = " + modifiers; tmpString = KeyEvent.getModifiersExText(modifiers); if (tmpString.length() > 0) { modString += " (" + tmpString + ")"; } else { modString += " (no modifiers)"; } actionString = "action key? "; if (e.isActionKey()) { actionString += "YES"; } else { actionString += "NO"; } locationString = "key location: "; int location = e.getKeyLocation(); if (location == KeyEvent.KEY_LOCATION_STANDARD) { locationString += "standard"; } else if (location == KeyEvent.KEY_LOCATION_LEFT) { locationString += "left"; } else if (location == KeyEvent.KEY_LOCATION_RIGHT) { locationString += "right"; } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) { locationString += "numpad"; } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN) locationString += "unknown"; } <em>...//Display information about the KeyEvent...</em> }}</pre></blockquote></blockquote><h3><a name="api">The Key Listener API</a></h3><blockquote><p align=center><a name="keylistener">The KeyListener Interface</a><p><em>The corresponding adapter class is<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyAdapter.html"><code>KeyAdapter</code></a>.</em><table border=1><tr><th align=left>Method</th><th align=left>Purpose</th></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyListener.html#keyTyped(java.awt.event.KeyEvent)">keyTyped(KeyEvent)</a></td><td> Called just after the user types a Unicode character into the listened-to component.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyListener.html#keyPressed(java.awt.event.keyPressed)">keyPressed(KeyEvent)</a></td><td> Called just after the user presses a key while the listened-to component has the focus.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyListener.html#keyReleased(java.awt.event.KeyEvent)">keyReleased(KeyEvent)</a></td><td> Called just after the user releases a key while the listened-to component has the focus.</td></tr></table><p align=center><a name="keyevent">The KeyEvent Class</a><p>The <code>KeyEvent</code> class inherits many usefulmethods from the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/InputEvent.html"><code>InputEvent</code></a> class, such as <code>getModifiersEx</code>, and a coupleuseful methods from the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/ComponentEvent.html"><code>ComponentEvent</code></a> and<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/AWTEvent.html"><code>AWTEvent</code></a> classes. See the<a href=mouselistener.html#inputevent>InputEvent Class</a>table in the <a href=mouselistener.html>mouse listener</a> page fora complete list.<table border=1><tr><th align=left>Method</th><th align=left>Purpose</th></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyChar()">int getKeyChar()</a></td><td> Get the Unicode character associated with this event. Only rely on this value for key-typed events.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()">int getKeyCode()</a></td><td>Get the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. The <code>KeyEvent</code> class defines many key code constants for commonly seen keys. For example, <code>VK_A</code> specifies the key labeled <b>A</b>, and <code>VK_ESCAPE</code> specifies the Escape key.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyText(int)">String getKeyText(int)</a><br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyModifiersText(int)">String getKeyModifiersText(int)</a></td><td>Return text descriptions of the event's key code and modifier keys, respectively. Note that the <code>InputEvent</code> methods <code>getModifiersEx</code> and <code>getModifiersExText</code>, introduced in release 1.4, provide more information about the key event than <code>getModifiers</code>, <code>getKeyText</code>, and <code>getKeyModifiersText</code>. For this reason, the 1.4 methods are preferred.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#isActionKey()">boolean isActionKey()</a></td><td>Return true if the key firing the event is an action key. Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys. This information is valid only for key-pressed and key-released events.</td></tr><tr><td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyLocation()">int getKeyLocation()</a></td><td>Return the location of the key that fired this event. This provides a way to distinguish keys that occur more than once on a keyboard, such as the two shift keys, for example. The possible values are <code>KEY_LOCATION_STANDARD</code>, <code>KEY_LOCATION_LEFT</code>, <code>KEY_LOCATION_RIGHT</code>, <code>KEY_LOCATION_NUMPAD</code>, or <code>KEY_LOCATION_UNKNOWN</code>. This method always returns <code>KEY_LOCATION_UNKNOWN</code> for key-typed events. Introduced in release 1.4.</td></tr></table></font></blockquote><a name="eg"><h3>Examples that Use Key Listeners</h3></a><blockquote>The following table lists theexamples that use key listeners. <p> <table><tr><th align=left> Example</th><th align=left> Where Described</th><th align=left> Notes</th></tr><tr valign=top><td> <a href="examples/index.html#KeyEventDemo"><code>KeyEventDemo</code></a></td><td> This section</td><td> Reports all key events that occur on a text field to demonstrate the circumstances under which key events are fired.</td></tr></table> </blockquote> <div class=NavBit> <a target=_top href=itemlistener.html>« Previous</a> • <a target=_top href=../TOC.html>Trail</a> • <a target=_top href=listdatalistener.html>Next »</a> </div> </div> <div id=Footer><div id=TagNotes> Problems with the examples? Try <a target="_blank" href=../../information/run-examples.html>Compiling and Running the Examples: FAQs</a>. <br> Complaints? Compliments? Suggestions? <a target="_blank" href="http://developer.sun.com/contact/tutorial_feedback.jsp">Give us your feedback</a>.<br><br> <a target="_blank" href="../../information/copyright.html">Copyright</a> 1995-2006 Sun Microsystems, Inc. All rights reserved. <span id=Download></span></div> </div> <div class=PrintHeaders> <b>Previous page:</b> How to Write an Item Listener <br><b>Next page:</b> How to Write a List Data Listener </div> </body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -