DDOOCP Key Listen

download DDOOCP Key Listen

of 56

description

ိ္ိ

Transcript of DDOOCP Key Listen

15.21.3.How to Write a Key Listener

importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;

importjavax.swing.JFrame;importjavax.swing.JTextField;

publicclassUsingKeyListener{publicstaticvoidmain(String[]args){JFrameaWindow=newJFrame("ThisistheWindowTitle");

aWindow.setBounds(50,100,300,300);aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextFieldtypingArea=newJTextField(20);typingArea.addKeyListener(newKeyListener(){

/**Handlethekeytypedeventfromthetextfield.*/publicvoidkeyTyped(KeyEvente){displayInfo(e,"KEYTYPED:");}

/**Handlethekeypressedeventfromthetextfield.*/publicvoidkeyPressed(KeyEvente){displayInfo(e,"KEYPRESSED:");}

/**Handlethekeyreleasedeventfromthetextfield.*/publicvoidkeyReleased(KeyEvente){displayInfo(e,"KEYRELEASED:");}

protectedvoiddisplayInfo(KeyEvente,Strings){StringkeyString,modString,tmpString,actionString,locationString;

//Youshouldonlyrelyonthekeychariftheevent//isakeytypedevent.intid=e.getID();if(id==KeyEvent.KEY_TYPED){charc=e.getKeyChar();keyString="keycharacter='"+c+"'";}else{intkeyCode=e.getKeyCode();keyString="keycode="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";}

intmodifiers=e.getModifiersEx();modString="modifiers="+modifiers;tmpString=KeyEvent.getModifiersExText(modifiers);if(tmpString.length()>0){modString+="("+tmpString+")";}else{modString+="(nomodifiers)";}

actionString="actionkey?";if(e.isActionKey()){actionString+="YES";}else{actionString+="NO";}

locationString="keylocation:";intlocation=e.getKeyLocation();if(location==KeyEvent.KEY_LOCATION_STANDARD){locationString+="standard";}elseif(location==KeyEvent.KEY_LOCATION_LEFT){locationString+="left";}elseif(location==KeyEvent.KEY_LOCATION_RIGHT){locationString+="right";}elseif(location==KeyEvent.KEY_LOCATION_NUMPAD){locationString+="numpad";}else{//(location==KeyEvent.KEY_LOCATION_UNKNOWN)locationString+="unknown";}

System.out.println(keyString);System.out.println(modString);System.out.println(actionString);System.out.println(locationString);}

});aWindow.add(typingArea);aWindow.setVisible(true);}}

****************************************8_____________________-import javax.swing.*;import java.awt.*;import java.awt.event.*;

/** * Listen to keys typed */

public class KeyListenerFrame extends JFrame implements KeyListener { GridLayout gridLayout1 = new GridLayout(); JPanel listenerPan = new JPanel();

public KeyListenerFrame() { try { jbInit(); listenerPan.addKeyListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); listenerPan.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0,true), "showKey"); listenerPan.getActionMap().put("showKey", showKey);

} catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { KeyListenerFrame klf = new KeyListenerFrame(); klf.setBounds(10,10,200,200); klf.setVisible(true); klf.focusPanel(); } public void focusPanel() { listenerPan.requestFocus(); } private void jbInit() throws Exception { this.getContentPane().setLayout(gridLayout1); this.getContentPane().add(listenerPan, null); } Action showKey = new AbstractAction() { public void actionPerformed(ActionEvent e) { System.out.println("VK_PAGE_UP"); } };

public void keyTyped(KeyEvent e) { System.out.println(e.toString()); } public void keyPressed(KeyEvent e) { System.out.println(e.toString()); } public void keyReleased(KeyEvent e) { System.out.println(e.toString()); }}

****************______________*******************888How to use KeyListener and ActionListener Java Code: import java.awt.AWTEventMulticaster;import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;

import javax.swing.JFrame;import javax.swing.JTextField;

public class KeyTextTester { public static void main(String args[]) { JFrame frame = new JFrame("Key Text Sample"); KeyTextComponent keyTextComponent = new KeyTextComponent(); final JTextField textField = new JTextField();

ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { String keyText = actionEvent.getActionCommand(); textField.setText(keyText); } }; keyTextComponent.addActionListener(actionListener);

Container contentPane = frame.getContentPane(); contentPane.add(keyTextComponent, BorderLayout.CENTER); contentPane.add(textField, BorderLayout.SOUTH); frame.setSize(300, 200); frame.setVisible(true); }}

class KeyTextComponent extends Canvas { private ActionListener actionListenerList = null;

public KeyTextComponent() { setBackground(Color.cyan); KeyListener internalKeyListener = new KeyAdapter() { public void keyPressed(KeyEvent keyEvent) { if (actionListenerList != null) { int keyCode = keyEvent.getKeyCode(); String keyText = KeyEvent.getKeyText(keyCode); ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, keyText); actionListenerList.actionPerformed(actionEvent); } } };

MouseListener internalMouseListener = new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { requestFocus(); } };

addKeyListener(internalKeyListener); addMouseListener(internalMouseListener); }

public void addActionListener(ActionListener actionListener) { actionListenerList = AWTEventMulticaster.add(actionListenerList, actionListener); }

public void removeActionListener(ActionListener actionListener) { actionListenerList = AWTEventMulticaster.remove(actionListenerList, actionListener); }

public boolean isFocusTraversable() { return true; }}

***************_______________******************

Listening for key events in a Java applicationHow can I listen for key events in a Java application?Attached is a simple Java application that listens for key events. When a key is pressed in the text field, it will display its keycode in the text box. If it recognizes a function key, it will also display the function key name.It listens for F10, F12 without unregistering them first. For F11, it always reports 229 for the key code even afterit's unregistered. You may use this application to find the keycode for the keys you are interested in. For instance, if you get a KeyEvent with the key code of 229, you know it's F11.This application has code that calls into a native library called FuncKeysJni.dll which unregisters certain function keys such as F1, F2, F6 and F7 which most people struggle with. The sample application includes theJava and JNI source code.File Attachments ******************______**********************Writing a Key Listener Key events tell you when the user types at the keyboard. Specifically, key events are generated by the component with the keyboard focus when the user presses or releases keyboard keys. (For information about focus, see the focus discussion in Writing a Focus Listener.) You can be notified about two basic kinds of key events: the typing of a Unicode character, and the pressing or releasing of a key on the keyboard. The first kind of event is called a key typed event. The second kind are key pressed and key released events. In general, you should try to use key typed events unless you need to know when the user presses keys that don't correspond to characters. For example, if you want to know when the user types some Unicode character -- even one that results from the user pressing several keys in sequence -- listen for key typed events. On the other hand, if you want to know when the user presses the F1 character, you need to listen for key pressed/released events. If you need to detect key events fired by a custom component, make sure the component requests the keyboard focus. Otherwise, it'll never get the focus and thus never fire key events. Key Event MethodsThe KeyListener interface and its corresponding adapter class, KeyAdapter, contain three methods: void keyTyped(KeyEvent) Called by the AWT just after the user types a Unicode character into the listened-to component. void keyPressed(KeyEvent) Called by the AWT just after the user presses a key on the keyboard. void keyReleased(KeyEvent) Called by the AWT just after the user releases a key on the keyboard. Examples of Handling Key EventsThe following applet 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 applet lets you clear both the text field and text area.

Try this: 1. Click in the applet's text field so that it gets the keyboard focus. 2. Press and release the A key on the keyboard. 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; they also don't have modifier information. If you care only about which characters the user types, you should handle key typed events. If you care about which keys the user presses/releases, you should handle key pressed/released events. 3. Press the Clear button. You might want to do this after each of the following steps. 4. Press and release the Shift key. The text field fires two events: a key pressed and a key released. The text field doesn't generate a key typed event because Shift, by itself, doesn't correspond to any character. 5. Type an uppercase A by pressing the Shift and A keys. You'll see the following events, although perhaps not in this order: key press (Shift), key press (A), key typed ('A'), key release (A), key release (Shift). 6. Type an uppercase A by pressing and releasing the Caps Lock key, and then pressing the A key. You should see the following events: key press (Caps Lock), key press (A), key typed ('A'), key release (A). Notice that the Caps Lock key doesn't generate a key release event until you press and release it again. The same is true of other state keys, such as Scroll Lock and Num Lock. 7. Press and hold the A key. Does it automatically repeat? If so, you'll see the same events that you would have seen if you pressed and released the A key repeatedly.

You can find the applet's code in KeyDemo.java. Here is the applet's key event handling code: public class KeyDemo ... implements KeyListener ... { ...//where initialization occurs:typingArea = new TextField(20);typingArea.addKeyListener(this); ... /** 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){...char c = e.getKeyChar();int keyCode = e.getKeyCode();int modifiers = e.getModifiers();...tmpString = KeyEvent.getKeyModifiersText(modifiers);

...//display information about the KeyEvent... }}You can find more examples of key listeners in the following sections: [LIST GOES HERE] The KeyEvent ClassEach key event method has a single parameter: a KeyEvent object. The KeyEvent class defines the following useful methods: int getKeyChar() void setKeyChar(char) Get or set the key character associated with this key typed [CHECK] event. The key character is a Unicode character. int getKeyCode() void setKeyCode(int) Get or set the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. The KeyEvent class defines many key code constants for commonly seen keys. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the ESCAPE key. void setModifiers(int) Sets the state of the modifier keys for this event. Also see the InputEvent getModifiers method. Other potentially useful methods in KeyEvent include methods that generate localizable text descriptions of key codes and modifier keys. The KeyEvent class extends InputEvent, which extends ComponentEvent. ComponentEvent provides the handy getComponent method. InputEvent provides the following useful methods: int getWhen() Returns the timestamp of when this event occurred. The higher the timestamp, the more recently the event occurred. [CHECK!] boolean isAltDown() boolean isControlDown() boolean isMetaDown() boolean isShiftDown() Convenient methods giving you the state of the modifier keys when the event was generated. int getModifiers() Returns a flag indicating the state of all the modifier keys when the event was generated. ****************_______________*******************How to Write a Key ListenerKey events indicate when the user is typing at the keyboard. Specifically, key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys. For detailed information about focus, see How to Use the Focus Subsystem.

Note:To define special reactions to particular keys, use key bindings instead of a key listener. For further information, see How to Use Key Bindings.

Notifications are sent about two basic kinds of key events: The typing of a Unicode character The pressing or releasing of a key on the keyboardThe first kind of event is called a key-typed event. The second kind is either a key-pressed or key-released event.In general, you react to only key-typed events unless you need to know when the user presses keys that do not correspond to characters. For example, to know when the user types a Unicode character ??? whether by pressing one key such as 'a' or by pressing several keys in sequence ??? you handle key-typed events. On the other hand, to know when the user presses the F1 key, or whether the user pressed the '3' key on the number pad, you handle key-pressed events.

Note:To fire keyboard events, a component must have the keyboard focus.

To make a component get the keyboard focus, follow these steps:1. Make sure the component's isFocusable method returns true. This state allows the component to receive the focus. For example, you can enable keyboard focus for a JLabel component by calling the setFocusable(true) method on the label.2. Make sure the component requests the focus when appropriate. For custom components, implement a mouse listener that calls the requestFocusInWindow method when the component is clicked.

Version note:This page reflects the focus API introduced in JDK release 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can callcomponent.setFocusTraversalKeysEnabled(false)on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use the KeyEventDispatcher class to pre-listen to all key events. The focus page has detailed information on the focus subsystem.

You can obtain detailed information about a particular key-pressed event. For example, you can query a key-pressed event to determine if it was fired from an action key. Examples of action keys include Copy, Paste, Page Up, Undo, and the arrow and function keys. As of JDK release 1.4, you can also query a key-pressed or key-released event to determine the location of the key that fired the event. Most key events are fired from the standard keyboard, but the events for some keys, such as Shift, have information on whether the user pressed the Shift key on the 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.For key-typed events you can obtain the key character value as well as any modifiers used.

Note:You should not rely on the key character value returned from getKeyChar unless it is involved in a key-typed event.

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.

Try this:1. Click the Launch button to run KeyEventDemo using Java Web Start (download JDK 6 or later). Alternatively, to compile and run the example yourself, consult the example index.2. Type a lowercase 'a' by pressing and releasing the A key on the keyboard.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.3. Press the Clear button.You might want to do this after each of the following steps.4. Press and release the Shift key.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.5. Type an uppercase 'A' by pressing the Shift and A keys.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.6. Type an uppercase 'A' by pressing and releasing the Caps Lock key, and then pressing the A key.You should see the following events: key-pressed (Caps Lock), key-pressed (A), key typed ('A'), key-released (A). Note that Caps Lock is not listed as a modifier key.7. 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.8. Press a function key, such as F3. You'll see that the function key is an action key.9. Press the left Shift key, followed by the right Shift key. The key-pressed and key-released events indicate which Shift key was typed.10. Press the Num Lock key if your keyboard has a number pad.As for Caps Lock, there is a key-pressed event, but no key-released event.11. Press the '2' key on the number pad. You see the key-pressed, key-typed, and key-released events for the number '2'.12. 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.13. Press the Num Lock key again. A key-released event is fired.

You can find the example's code in KeyEventDemo.java. Here is the demo's key event handling code:public class KeyEventDemo ... implements KeyListener ... { ...//where initialization occurs: 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: "); } ... private void displayInfo(KeyEvent e, String keyStatus){ //You should only rely on the key char if the event //is a key typed event. int id = e.getID(); String keyString; 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 modifiersEx = e.getModifiersEx(); String modString = "extended modifiers = " + modifiersEx; String tmpString = KeyEvent.getModifiersExText(modifiersEx); if (tmpString.length() > 0) { modString += " (" + tmpString + ")"; } else { modString += " (no extended modifiers)"; } String actionString = "action key? "; if (e.isActionKey()) { actionString += "YES"; } else { actionString += "NO"; } String 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"; } ...//Display information about the KeyEvent... }}The Key Listener APIThe KeyListener InterfaceThe corresponding adapter class is KeyAdapter.MethodPurpose

keyTyped(KeyEvent)Called just after the user types a Unicode character into the listened-to component.

keyPressed(KeyEvent)Called just after the user presses a key while the listened-to component has the focus.

keyReleased(KeyEvent)Called just after the user releases a key while the listened-to component has the focus.

The KeyEvent ClassThe KeyEvent class inherits many useful methods from the InputEvent class, such as getModifiersEx, and a couple of useful methods from the ComponentEvent and AWTEvent classes. See the InputEvent Class table in the mouse listener page for a complete list.MethodPurpose

int getKeyChar()Obtains the Unicode character associated with this event. Only rely on this value for key-typed events.

int getKeyCode()Obtains the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. The KeyEvent class defines many key code constants for commonly seen keys. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the Escape key.

String getKeyText(int)String getKeyModifiersText(int)Return text descriptions of the event's key code and modifier keys, respectively.

int getModifiersEx() String getModifiersExText(int modifiers)Return the extended modifiers mask for this event. There are methods inherited from the InputEvent class. Extended modifiers represent the state of all modal keys. The getModifiersExText method returns a string describing the extended modifier keys and mouse buttons. Since the getModifiersEx and getModifiersExText methods provide more information about key events, they are preferred over the getKeyText or getKeyModifiersText methods.

boolean isActionKey()Returns 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.

int getKeyLocation()Returns 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 KEY_LOCATION_STANDARD, KEY_LOCATION_LEFT, KEY_LOCATION_RIGHT, KEY_LOCATION_NUMPAD, or KEY_LOCATION_UNKNOWN. This method always returns KEY_LOCATION_UNKNOWN for key-typed events. Introduced in JDK release 1.4.

Examples that Use Key ListenersThe following table lists the examples that use key listeners.ExampleWhere DescribedNotes

KeyEventDemoThis sectionReports all key events that occur on a text field to demonstrate the circumstances under which key events are fired.

Previous Trail Next ******************__________________*********************

java.awt.event Interface KeyListenerAll Superinterfaces: EventListenerAll Known Implementing Classes: AWTEventMulticaster, BasicTableUI.KeyHandler, KeyAdapter

public interface KeyListenerextends EventListenerThe listener interface for receiving keyboard events (keystrokes). The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a component using the component's addKeyListener method. A keyboard event is generated when a key is pressed, released, or typed (pressedn and released). The relevant method in the listener object is then invoked, and the KeyEvent is passed to it. Since:1.1See Also:KeyAdapter, KeyEvent, Tutorial: Writing a Key Listener, Reference: The Java Class Libraries (update file)

Method Summary

voidkeyPressed(KeyEvente) Invoked when a key has been pressed.

voidkeyReleased(KeyEvente) Invoked when a key has been released.

voidkeyTyped(KeyEvente) Invoked when a key has been typed.

Method Detail

keyTypedpublic void keyTyped(KeyEvente)Invoked when a key has been typed. See the class description for KeyEvent for a definition of a key typed event.

keyPressedpublic void keyPressed(KeyEvente)Invoked when a key has been pressed. See the class description for KeyEvent for a definition of a key pressed event.

keyReleasedpublic void keyReleased(KeyEvente)Invoked when a key has been released. See the class description for KeyEvent for a definition of a key released event. *******************_____________________******************How to use KeyListenerPosted on: April 17, 2007 at 12:00 AM This section provides an example that implements keyListener in java.How to use KeyListener IntroductionIn this section, you will learn how to handle different key events on the Java Awt component by using the event handling in Java. When the given program is executed then you will see the several key events these are applied on the component like the key pressed, key release and so on.All the key events are handled through the KeyListener Interface that has been implemented in the main class of the program.Description of this program:In this program, you will see how to show display the specific massage on the frame according to the event. When you press the key then the message "Key Pressed" will be seen on the frame and if when you stop pressing keys then the message "Key Released" will be seen.This is possible by using the KeyListener interface. It will generate the KeyEvent and you can the check the exact event by using different method like the keyTyped(), keyPressed() and the keyReleased() method which are used for retrieving the generated specific event.Here is the code of this program:importjava.awt.*;importjava.awt.event.*;publicclassKeyListenerTesterextendsFrameimplementsKeyListener{TextFieldt1;Labell1;publicKeyListenerTester(Strings){super(s);Panelp=newPanel();l1=newLabel("KeyListener!");p.add(l1);add(p);addKeyListener(this);setSize(200,100);setVisible(true);addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){System.exit(0);}});}publicvoidkeyTyped(KeyEvente){ l1.setText("KeyTyped");}publicvoidkeyPressed(KeyEvente){l1.setText("KeyPressed");}publicvoidkeyReleased(KeyEvente){l1.setText("KeyReleased");}publicstaticvoidmain(String[]args){newKeyListenerTester("KeyListenerTester");}}

Output of program:

************___________***************Java Global JFrame Key ListenerSeptember 16, 2011 12:28 pm / 1 Comment / Jonathan Weatherhead Do you know what happens when you add a KeyListener to JFrame to capture global keystrokes? Nothing.Much to my frustration, I discovered recently that KeyEvents are not bubbled up through the JComponent hierarchy by default. The only component that consumes the event is the one currently focused. This means that As soon as you add children to the JFrame, the focus is stolen from the JFrame which can no longer capture global key events.Fortunately, there is an easy fix that I will show you. It involves providing a custom KeyEventDispatcher to the keyboard manager, catching the event before it reaches any of the JComponents.//Hijack the keyboard managerKeyboardFocusManager manager =KeyboardFocusManager.getCurrentKeyboardFocusManager();manager.addKeyEventDispatcher( new KeyDispatcher() );//Custom dispatcherclass KeyDispatcher implements KeyEventDispatcher {public boolean dispatchKeyEvent(KeyEvent e) {if(e.getID() == KeyEvent.KEY_TYPED)System.out.println( "typed" + e.getCharCode() )//Allow the event to be redispatchedreturn false;}}

************______________********************

The KeyListener InterfaceThe interface has three methods that must be implemented by a class:public interface KeyListener{

public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e);

}The keyPressed method and the keyReleased method are called when any key is pressed down or released respectively. The keyTyped method is only called when a valid Unicode character is entered. For example, if the user holds the SHIFT key down, the keyPressed method is invoked. When the user releases the SHIFT key the keyReleased method is invoked. But unless the user presses the SHIFT key and a character key (i.e., any letter or number) together the keyTyped is not invoked.The KeyEvent ObjectThe KeyEvent object is passed to a KeyListener method when it is called. It contains information about the key event that has occurred. The KeyEvent object has some useful methods, including: getKeyChar - returns the character for the key event. getKeyCode - returns the Unicode value for the character of the key event isActionKey - .a boolean value determining if the key is classed as an action key (e.g., Enter key, Delete key)Using the information in these methods helps to determine the key(s) that fired the key event. Implementing the KeyListener InterfaceLet's implement the KeyListener interface for a JTextArea component. Here's the listing for a simple GUI that uses a JFrame to hold two JTextAreas - one will listen for the key events and the other will sit inside a JScrollPane providing feedback about the key events being triggered:import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JTextArea;import javax.swing.JScrollPane;

public class KeyListenerExample { JTextArea inputText; JTextArea feedbackText;

//Note: Typically the main method will be in a //separate class. As this is a simple one class //example it's all in the one class. public static void main(String[] args) {

//Use the event dispatch thread for Swing components EventQueue.invokeLater(new Runnable() { @Override public void run() { new KeyListenerExample(); } }); } public KeyListenerExample() { JFrame guiFrame = new JFrame(); //make sure the program exits when the frame closes guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); guiFrame.setTitle("Creating a Table Example"); guiFrame.setSize(700,200); //This will center the JFrame in the middle of the screen guiFrame.setLocationRelativeTo(null); feedbackText = new JTextArea(); JScrollPane scrollText = new JScrollPane(feedbackText); inputText = new JTextArea();

//place keylistener code here guiFrame.add(inputText, BorderLayout.NORTH); guiFrame.add(scrollText, BorderLayout.CENTER); guiFrame.setVisible(true); } }First add the import statements for the KeyListener interface and KeyEvent object to the top of the class: import java.awt.event.KeyEvent;import java.awt.event.KeyListener;Now, we can implement the KeyListener as an anonymous inner class attached to the inputText JTextArea by using the addKeyListener method:inputText.addKeyListener(new KeyListener(){ @Override public void keyPressed(KeyEvent e) { feedbackText.append("Key Pressed: " + e.getKeyChar() + "\n"); }

@Override public void keyReleased(KeyEvent e) { feedbackText.append("Key Released: " + e.getKeyChar() + "\n"); } @Override public void keyTyped(KeyEvent e) { feedbackText.append("Key Typed: " + e.getKeyChar() + " " + KeyEvent.getKeyModifiersText(e.getModifiers()) + "\n"); }});The text that is appended to the feedbackText JTextArea will depend on the keys that the user types into the inputText JTextArea. If the user presses a normal character key then all three methods will be called in order of keyPressed, keyReleased and keyTyped. If the user just types the SHIFT key then only the keyPressed and keyReleased methods will be invoked.The full Java code listing can be found in A KeyListener Example Program.***********_____________**************importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;

importjavax.swing.JFrame;importjavax.swing.JTextField;

publicclassKeyTest{publicstaticvoidmain(Stringargs[]){JFrameframe=newJFrame("KeyListener");ContainercontentPane=frame.getContentPane();

KeyListenerlistener=newKeyListener(){publicvoidkeyPressed(KeyEvente){dumpInfo("Pressed",e);}

publicvoidkeyReleased(KeyEvente){dumpInfo("Released",e);}

publicvoidkeyTyped(KeyEvente){dumpInfo("Typed",e);}

privatevoiddumpInfo(Strings,KeyEvente){System.out.println(s);intcode=e.getKeyCode();System.out.println("\tCode:"+KeyEvent.getKeyText(code));System.out.println("\tChar:"+e.getKeyChar());intmods=e.getModifiersEx();System.out.println("\tMods:"+KeyEvent.getModifiersExText(mods));System.out.println("\tLocation:"+location(e.getKeyLocation()));System.out.println("\tAction?"+e.isActionKey());}

privateStringlocation(intlocation){switch(location){caseKeyEvent.KEY_LOCATION_LEFT:return"Left";caseKeyEvent.KEY_LOCATION_RIGHT:return"Right";caseKeyEvent.KEY_LOCATION_NUMPAD:return"NumPad";caseKeyEvent.KEY_LOCATION_STANDARD:return"Standard";caseKeyEvent.KEY_LOCATION_UNKNOWN:default:return"Unknown";}}};

JTextFieldtext=newJTextField();text.addKeyListener(listener);contentPane.add(text,BorderLayout.NORTH);frame.pack();frame.show();}}