40 likes | 48 Views
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.
E N D
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
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
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
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.