CIS 35A: Introduction to Java Programming

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

Events

Events
Code low-level events
Adapter

How to work with adapter classes

  • An adapter class is a class that implements all the methods of a listener interface as empty methods. Then, an event listener class that inherits an adapter class must override only the methods that the program needs.

Common adapter classes

Class Interface
WindowAdapter WindowListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener

The AutoSelect class using FocusAdapter

public class AutoSelect extends FocusAdapter
{
    public void focusGained(FocusEvent e)
    {
        if (e.getComponent() instanceof JTextField)
        {
            JTextField t = (JTextField) e.getComponent();
            t.selectAll();
        }
    }
}

The NumFilter class using KeyAdapter

public class NumFilter extends KeyAdapter
{
    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();
    }
}
Previous | Summary | Focus | Keyboard | Adapter | Next