1 / 4

Key Events

Learn how to handle key events in Java by implementing the KeyListener interface and using KeyEvent objects. Find out how to determine which key was pressed and detect modifier keys.

egrant
Download Presentation

Key Events

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Key Events • A key event is generated when • the user types on the keyboard • Listeners for key events are created • By implementing the KeyListener interface • A KeyEvent object is • passed to the appropriate method • when a key event occurs

  2. Key Events (cont’d) • The component that generates a key event is • the one that has the current keyboard focus • Constants in the KeyEvent class can be used • to determine which key was pressed • The following example "moves" an image of an arrow • as the user types the keyboard arrow keys • See DirectionFrame.java and DirectionPanel.java

  3. Key Events (cont’d) • KeyEvent method getKeyCode • gets the virtual key code of the pressed key • returns a value that can be passed to • static KeyEvent method getKeyText to get a string • containing the name of the key that was pressed • KeyEvent method isActionKey • determines whether the key in the event was an action key

  4. Key Events (cont’d) • Method getModifiers determines whether • any modifier keys (such as Shift, Alt and Ctrl) • were pressed when the key event occurred. • Result can be passed to static KeyEvent method • getKeyModifiersText to get a string • containing the names of the pressed modifier keys. • InputEvent methods • isAltDown, isControlDown, isMetaDown, isShiftDown • each return a boolean indicating whether • the particular key was pressed during the key event.

More Related