CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Events

Events
Code low-level events
Keyboard

How to work with keyboard events

  • A keyboard event occurs when a user presses, releases, or presses and releases a key.
  • The KeyEvent class inherits the InputEvent class.

Methods of the KeyListener interface

Method Description
void keyPressed(KeyEvent e) Invoked when a key is pressed.
void keyReleased(KeyEvent e) Invoked when a key is released.
void keyTyped(KeyEvent e) Invoked when a key is pressed and released.

Common methods of the KeyEvent class

Method Description
getKeyCode() Returns an int code that represents the key pressed.
getKeyChar() Returns a char that represents the key pressed.
isControlDown() Returns a boolean that indicates if the Ctrl key is down.
isAltDown() Returns a boolean that indicates if the Alt key is down.
isShiftDown() Returns a boolean that indicates if the Shift key is down.

A method of the InputEvent class

Method Description
consume() Stops further processing of the event.

A class that implements the KeyListener interface

public class NumFilter implements KeyListener
{
    public void keyTyped(KeyEvent e)
    {
        char c = e.getKeyChar();
        if (   c != '0' && c != '1' && c != '2'
            && c != '3' && c != '4' && c != '5'
            && c != '6' && c != '7' && c != '8'
            && c != '9' && c != '.' && c != '+'
            && c != '-')
            e.consume();
    }

    public void keyPressed(KeyEvent e) {}

    public void keyReleased(KeyEvent e) {}
}

A text field that uses the key listener

paymentTextField = new JTextField(10);
paymentTextField.addKeyListener(new NumFilter());
displayPanel.add(paymentTextField);
Previous | Summary | Focus | Keyboard | Adapter | Next