banner



How To Register A Key Stroke In C

Key events indicate when the user is typing at the keyboard. Specifically, primal events are fired by the component with the keyboard focus when the user presses or releases keyboard keys. For detailed information about focus, come across How to Use the Focus Subsystem.


Annotation:

To ascertain special reactions to particular keys, utilize key bindings instead of a primal listener. For further information, see How to Utilize Key Bindings.


Notifications are sent about two basic kinds of key events:

  • The typing of a Unicode character
  • The pressing or releasing of a fundamental on the keyboard

The first kind of event is called a fundamental-typed result. The 2d kind is either a central-pressed or key-released upshot.

In general, you react to just cardinal-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 past 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 cardinal, or whether the user pressed the 'iii' primal on the number pad, you handle central-pressed events.


Notation:

To burn down keyboard events, a component must accept 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 past 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:

The focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you lot demand to prevent the focus traversal keys from beingness consumed, you can phone call

component.setFocusTraversalKeysEnabled(false)            

on the component that is firing the cardinal events. Your program must then handle focus traversal on its own. Alternatively, you tin can use the KeyEventDispatcher form 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 outcome. For instance, 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. Y'all can also query a cardinal-pressed or key-released event to decide the location of the central that fired the event. Virtually key events are fired from the standard keyboard, just the events for some keys, such as Shift, have data on whether the user pressed the Shift key on the left or the right side of the keyboard. Besides, the number 'ii' can be typed from either the standard keyboard or from the number pad.

For key-typed events you can obtain the cardinal grapheme value likewise as any modifiers used.


Note:

You should not rely on the key graphic symbol value returned from getKeyChar unless information technology is involved in a key-typed issue.


The following example demonstrates key events. It consists of a text field that you can blazon into, followed by a text area that displays a message every fourth dimension the text field fires a key result. A button at the lesser of the window lets you lot clear both the text field and text surface area.

KeyEventDemo.html

Try this:

  1. Click the Launch push button to run KeyEventDemo using Java™ Web Get-go (download JDK 7 or after). Alternatively, to compile and run the example yourself, consult the example index.Launches the KeyEventDemo application
  2. Type a lowercase 'a' by pressing and releasing the A central on the keyboard.
    The text field fires three events: a key-pressed consequence, a key-typed event, and a fundamental-released event. Notation that the fundamental-typed event doesn't accept primal code information, and cardinal-pressed and cardinal-released events don't have cardinal grapheme information. None of the events so far are from modifier or activity keys and the key location, reported on the key-pressed and key-released events, is most likely standard.
  3. Printing the Clear button.
    You lot might want to practise this later each of the post-obit 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 fundamental-typed event because Shift, past itself, doesn't correspond to whatsoever character.
  5. Type an uppercase 'A' by pressing the Shift and A keys.
    You'll run across the post-obit events, although perhaps not in this order: primal-pressed (Shift), key-pressed (A), fundamental typed ('A'), key-released (A), key-released (Shift). Annotation that Shift is listed every bit the modifier primal for the key-typed and fundamental-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), central typed ('A'), fundamental-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 past the central result listener. This is considering the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. Press Tab twice more than to return the focus to the text expanse.
  8. Press a function central, such as F3. You'll encounter that the function fundamental is an action key.
  9. Printing the left Shift central, followed by the right Shift key. The key-pressed and key-released events point which Shift central was typed.
  10. Press the Num Lock key if your keyboard has a number pad.
    Every bit for Caps Lock, there is a key-pressed event, merely no central-released upshot.
  11. Press the 'ii' primal on the number pad. You meet the key-pressed, key-typed, and key-released events for the number '2'.
  12. Press the '2' key on the standard keyboard. Again, you run across the three event messages. The cardinal-typed events for both number ii keys are identical. But the key-pressed and key-released events bespeak different key codes and unlike key locations.
  13. Press the Num Lock key again. A primal-released issue is fired.

You can find the example'due south lawmaking in KeyEventDemo.java. Here is the demo's central event treatment 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          //get bachelor to the key event listener.         //typingArea.setFocusTraversalKeysEnabled(faux);     ...     /** Handle the key typed issue from the text field. */     public void keyTyped(KeyEvent due east) {         displayInfo(e, "KEY TYPED: ");     }      /** Handle the primal-pressed result from the text field. */     public void keyPressed(KeyEvent east) {         displayInfo(e, "Fundamental PRESSED: ");     }      /** Handle the cardinal-released event from the text field. */     public void keyReleased(KeyEvent due east) {         displayInfo(e, "KEY RELEASED: ");     }     ...     private void displayInfo(KeyEvent east, String keyStatus){                  //You should only rely on the cardinal char if the event         //is a key typed event.         int id = east.getID();         String keyString;         if (id == KeyEvent.KEY_TYPED) {             char c = eastward.getKeyChar();             keyString = "key character = '" + c + "'";         } else {             int keyCode = e.getKeyCode();             keyString = "cardinal code = " + keyCode                     + " ("                     + KeyEvent.getKeyText(keyCode)                     + ")";         }                  int modifiersEx = e.getModifiersEx();         Cord 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 (due east.isActionKey()) {             actionString += "YES";         } else {             actionString += "NO";         }                  String locationString = "central 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 Fundamental Listener API

The KeyListener Interface

The corresponding adapter class is KeyAdapter.

Method Purpose
keyTyped(KeyEvent) Called just after the user types a Unicode character into the listened-to component.
keyPressed(KeyEvent) Chosen just afterwards the user presses a key while the listened-to component has the focus.
keyReleased(KeyEvent) Called merely afterward the user releases a key while the listened-to component has the focus.

The KeyEvent Class

The KeyEvent course inherits many useful methods from the InputEvent class, such equally getModifiersEx, and a couple of useful methods from the ComponentEvent and AWTEvent classes. Run across the InputEvent Class table in the mouse listener folio for a complete list.

Method Purpose
int getKeyChar() Obtains the Unicode character associated with this result. 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 cardinal code constants for commonly seen keys. For example, VK_A specifies the cardinal labeled A, and VK_ESCAPE specifies the Escape key.
String getKeyText(int)
String getKeyModifiersText(int)
Return text descriptions of the event'southward cardinal lawmaking and modifier keys, respectively.
int getModifiersEx()
Cord getModifiersExText(int modifiers)
Return the extended modifiers mask for this issue. At that place are methods inherited from the InputEvent form. Extended modifiers correspond the state of all modal keys. The getModifiersExText method returns a cord describing the extended modifier keys and mouse buttons. Since the getModifiersEx and getModifiersExText methods provide more than data almost key events, they are preferred over the getKeyText or getKeyModifiersText methods.
boolean isActionKey() Returns true if the primal firing the event is an activity key. Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys. This data is valid only for cardinal-pressed and key-released events.
int getKeyLocation() Returns the location of the fundamental that fired this upshot. This provides a way to distinguish keys that occur more than one time on a keyboard, such as the 2 shift keys, for instance. The possible values are KEY_LOCATION_STANDARD, KEY_LOCATION_LEFT, KEY_LOCATION_RIGHT, KEY_LOCATION_NUMPAD, or KEY_LOCATION_UNKNOWN. This method e'er returns KEY_LOCATION_UNKNOWN for central-typed events.

Examples that Employ Key Listeners

The following table lists the examples that employ key listeners.

Example Where Described Notes
KeyEventDemo This section Reports all cardinal events that occur on a text field to demonstrate the circumstances under which primal events are fired.

How To Register A Key Stroke In C,

Source: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Posted by: stinsoniletelaid.blogspot.com

0 Response to "How To Register A Key Stroke In C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel