Event Classes and Listener Interfaces
Java Swing uses event classes to encapsulate details about events and listener interfaces to respond to those events. This is the basis of Swing’s event delegation model.
Event Classes
Event classes are found in java.awt.event
and javax.swing.event
packages. Each class corresponds to a type of user action.
Event Class | Description |
---|---|
ActionEvent | Generated by buttons, menus, etc. |
MouseEvent | Mouse actions like click, press |
KeyEvent | Keyboard input |
WindowEvent | Window state changes |
ItemEvent | Checkbox, radio button changes |
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
}
Listener Interfaces
Each event class has a corresponding listener interface.
Listener Interface | Handles | Event Class |
---|---|---|
ActionListener | Button clicks, menu selection | ActionEvent |
MouseListener | Mouse click, press, release, etc. | MouseEvent |
KeyListener | Key press, release, and typing | KeyEvent |
WindowListener | Window events | WindowEvent |
ItemListener | Item selection events | ItemEvent |
Adapter Classes
To simplify implementing listeners with many methods, Java provides adapter classes:
MouseAdapter
,KeyAdapter
,WindowAdapter
- You can override only the method you need.
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked!");
}
});