How To Use Keypressed In Java
Primal events point 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 Utilize the Focus Subsystem.
Annotation:
To ascertain special reactions to particular keys, use key bindings instead of a key listener. For further data, run into How to Utilize Key Bindings.
Notifications are sent well-nigh two basic kinds of key events:
- The typing of a Unicode character
- The pressing or releasing of a cardinal on the keyboard
The first kind of event is called a key-typed issue. The second kind is either a cardinal-pressed or key-released event.
In general, you react to only key-typed events unless you lot demand to know when the user presses keys that do not stand for 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 — yous handle cardinal-typed events. On the other hand, to know when the user presses the F1 primal, or whether the user pressed the '3' fundamental on the number pad, you handle primal-pressed events.
Annotation:
To burn down keyboard events, a component must have the keyboard focus.
To make a component get the keyboard focus, follow these steps:
- Make sure the component'south
isFocusable
method returnstrue
. This state allows the component to receive the focus. For example, you can enable keyboard focus for aJLabel
component past calling thesetFocusable(true)
method on the label. - 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 y'all need to prevent the focus traversal keys from being consumed, yous can call
component.setFocusTraversalKeysEnabled(false)
on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you tin use the KeyEventDispatcher
grade to pre-mind to all key events. The focus page has detailed information on the focus subsystem.
You can obtain detailed information about a detail key-pressed issue. For case, y'all can query a cardinal-pressed event to determine if it was fired from an action fundamental. Examples of action keys include Copy, Paste, Page Up, Undo, and the pointer and function keys. You can also query a key-pressed or key-released event to determine the location of the cardinal that fired the result. Most primal 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 fundamental on the left or the right side of the keyboard. Too, the number '2' can be typed from either the standard keyboard or from the number pad.
For primal-typed events you tin can obtain the central character value as well equally whatever modifiers used.
Notation:
You should not rely on the key character value returned from getKeyChar
unless information technology is involved in a key-typed event.
The following example demonstrates key events. Information technology consists of a text field that yous can type into, followed by a text area that displays a message every fourth dimension the text field fires a cardinal event. A button at the bottom of the window lets you clear both the text field and text expanse.
Try this:
- Click the Launch button to run KeyEventDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the instance index.
- Type a lowercase 'a' by pressing and releasing the A central on the keyboard.
The text field fires three events: a cardinal-pressed event, a key-typed event, and a central-released effect. Note that the cardinal-typed effect doesn't accept key code information, and key-pressed and key-released events don't have primal character information. None of the events so far are from modifier or activeness keys and the central location, reported on the cardinal-pressed and primal-released events, is most likely standard. - Press the Clear push.
You might desire to do this after each of the following steps. - Press and release the Shift key.
The text field fires two events: a central-pressed and a cardinal-released. The text field doesn't fire a key-typed event because Shift, by itself, doesn't correspond to whatsoever graphic symbol. - Type an uppercase 'A' by pressing the Shift and A keys.
You'll run across the following events, although perhaps not in this order: central-pressed (Shift), central-pressed (A), key typed ('A'), central-released (A), primal-released (Shift). Note that Shift is listed as the modifier key for the cardinal-typed and key-pressed events. - Type an uppercase 'A' by pressing and releasing the Caps Lock key, so pressing the A key.
You should meet the post-obit events: key-pressed (Caps Lock), fundamental-pressed (A), key typed ('A'), primal-released (A). Note that Caps Lock is not listed as a modifier key. - Printing the Tab cardinal. No Tab key-pressed or key-released events are received past the central event listener. This is considering the focus subsystem consumes focus traversal keys, such every bit Tab and Shift Tab. Printing Tab twice more to render the focus to the text area.
- Press a function key, such equally F3. Y'all'll see that the function key is an action key.
- Press the left Shift fundamental, followed by the right Shift key. The central-pressed and central-released events indicate which Shift key was typed.
- Printing the Num Lock key if your keyboard has a number pad.
Every bit for Caps Lock, there is a key-pressed upshot, but no key-released event. - Press the '2' key on the number pad. Yous meet the cardinal-pressed, key-typed, and key-released events for the number 'ii'.
- Printing the '2' primal on the standard keyboard. Again, y'all see the three event messages. The central-typed events for both number 2 keys are identical. Simply the key-pressed and fundamental-released events indicate different key codes and different cardinal locations.
- Press the Num Lock fundamental again. A fundamental-released event is fired.
You can detect the instance's code in KeyEventDemo.coffee
. Here is the demo's cardinal effect handling lawmaking:
public form KeyEventDemo ... implements KeyListener ... { ...//where initialization occurs: typingArea = new JTextField(xx); typingArea.addKeyListener(this); //Uncomment this if you wish to plough off focus //traversal. The focus subsystem consumes //focus traversal keys, such as Tab and Shift Tab. //If you lot uncomment the following line of code, this //disables focus traversal and the Tab events //get available to the key event listener. //typingArea.setFocusTraversalKeysEnabled(simulated); ... /** 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, "Fundamental PRESSED: "); } /** Handle the key-released result from the text field. */ public void keyReleased(KeyEvent eastward) { displayInfo(e, "KEY RELEASED: "); } ... private void displayInfo(KeyEvent due east, Cord keyStatus){ //Yous should only rely on the key char if the outcome //is a key typed effect. int id = due east.getID(); Cord keyString; if (id == KeyEvent.KEY_TYPED) { char c = east.getKeyChar(); keyString = "key character = '" + c + "'"; } else { int keyCode = e.getKeyCode(); keyString = "central 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)"; } Cord actionString = "action key? "; if (eastward.isActionKey()) { actionString += "YES"; } else { actionString += "NO"; } String locationString = "key location: "; int location = east.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 += "correct"; } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) { locationString += "numpad"; } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN) locationString += "unknown"; } ...//Display information about the KeyEvent... } }
The Central 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) | Called only afterwards the user presses a key while the listened-to component has the focus. |
keyReleased(KeyEvent) | Called simply after the user releases a key while the listened-to component has the focus. |
The KeyEvent Grade
The 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. Come across the InputEvent Class tabular array in the mouse listener folio for a complete listing.
Method | Purpose |
---|---|
int getKeyChar() | Obtains the Unicode character associated with this event. Only rely on this value for fundamental-typed events. |
int getKeyCode() | Obtains the primal code associated with this event. The cardinal lawmaking identifies the particular key on the keyboard that the user pressed or released. The KeyEvent class defines many central 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) | Render 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 activity key. Examples of action keys include Cut, Re-create, Paste, Page Upwards, 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 fundamental that fired this effect. This provides a way to distinguish keys that occur more than than in one case on a keyboard, such every bit 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 e'er returns KEY_LOCATION_UNKNOWN for key-typed events. |
Examples that Use Key Listeners
The following table lists the examples that use key listeners.
Example | Where Described | Notes |
---|---|---|
KeyEventDemo | This section | Reports all key events that occur on a text field to demonstrate the circumstances under which key events are fired. |
How To Use Keypressed In Java,
Source: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Posted by: owensgiand1987.blogspot.com
0 Response to "How To Use Keypressed In Java"
Post a Comment