Event Handling: Listeners
Site Admin
· 11 Sep 2026
· 1 views
The Delegation Model
AWT uses the delegation event model: a component fires events and registered listeners react. Register a listener with addXxxListener(...).
Button Action
btn.addActionListener(e -> status.setText("Clicked!"));Mouse Events
Implement MouseListener or extend MouseAdapter:
canvas.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
info.setText("Clicked at " + e.getX() + "," + e.getY());
}
});
Keyboard Events
Implement KeyListener to react to key presses:
field.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
System.out.println("Typed: " + e.getKeyChar());
}
});
Key Points
- Adapters (MouseAdapter, KeyAdapter) let you override only the methods you need.
- ActionListener is for buttons, text fields and menu items.
- Event objects carry details like coordinates and key codes.