Events And Listeners

Java's delegation event model is a specialized form of the Observer pattern.

Source (Observable)

Listener (Observer)

JComponent
listenerList : EventListenerList
+ addMouseListener(MouseListener)
+ removeMouseListener(MouseListener)
+ getMouseListeners() : MouseListener[]
# processMouseEvent(MouseEvent)
interested objects implement
<--- the interface and add themselves ---
to the source's listeners list

when the user clicks,
--- the source calls each listener's --->
mouseClicked method

MouseListener
+ mouseClicked(MouseEvent)
+ mouseEntered(MouseEvent)
+ mouseExited(MouseEvent)
+ mousePressed(MouseEvent)
+ mouseReleased(MouseEvent)

Swing has Listeners for low-, mid-, and high-level Events.

KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
WindowListener
more...
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
TextListener
more...
ActionListener
ChangeListener
DocumentListener
ListDataListener
PopupMenuListener
more...

Each Listener has one or more methods you must implement.

KeyListener
+ keyPressed(KeyEvent)
+ keyReleased(KeyEvent)
+ keyTyped(KeyEvent)
FocusListener
+ focusGained(FocusEvent)
+ focusLost(FocusEvent)
ActionListener
+ actionPerformed(ActionEvent)

Adapter classes implement Listeners with no-op methods.

KeyAdapter
+ KeyAdapter()
+ keyPressed(KeyEvent)
+ keyReleased(KeyEvent)
+ keyTyped(KeyEvent)
FocusAdapter
+ FocusAdapter()
+ focusGained(FocusEvent)
+ focusLost(FocusEvent)