←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Event Classes, Listener Interfaces & Adapter Classes in Java

Study material and explanations for Unit 4

Event Classes, Listener Interfaces & Adapter Classes in Java

1. Relationship Between Event Source, Event Class, Listener Interface & Methods

In Java’s Event Delegation Model, every GUI Event Source is paired with a specific Event Class (which acts as the parameter) and a corresponding Listener Interface (whose methods are called).

This master table covers all 9 Event Classes explicitly mentioned in your DAVV Unit 4 syllabus! Memorizing this table will help you answer almost any question from Unit 4:

Event Class (Parameter Passed) Event Source (Who Generates It?) Listener Interface Registration Method on Source Methods Called in Listener Interface
1. ActionEvent Button, List (double-click), MenuItem, TextField (Enter key) ActionListener addActionListener() actionPerformed(ActionEvent e)
2. ItemEvent Checkbox, Radio Button, Choice, List (single select) ItemListener addItemListener() itemStateChanged(ItemEvent e)
3. AdjustmentEvent Scrollbar AdjustmentListener addAdjustmentListener() adjustmentValueChanged(AdjustmentEvent e)
4. TextEvent TextField, TextArea (when text changes) TextListener addTextListener() textValueChanged(TextEvent e)
5. FocusEvent Any Component gaining or losing keyboard focus FocusListener addFocusListener() focusGained(FocusEvent e)
focusLost(FocusEvent e)
6. ContainerEvent Container (Frame, Panel) when component is added/removed ContainerListener addContainerListener() componentAdded(ContainerEvent e)
componentRemoved(ContainerEvent e)
7. KeyEvent Keyboard key pressed, released, or typed on a component KeyListener addKeyListener() keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
8. MouseEvent Mouse clicked, pressed, released, entered, exited, dragged, moved MouseListener &
MouseMotionListener
addMouseListener()
addMouseMotionListener()
5 methods in MouseListener
2 methods in MouseMotionListener
9. WindowEvent Window, Frame, Dialog (opened, closing, iconified, etc.) WindowListener addWindowListener() 7 methods (windowClosing(), windowOpened(), etc.)

2. Detailed Overview of the 9 Syllabus Event Classes

1. ActionEvent

  • Generated when a Button is clicked, a MenuItem is selected, a List item is double-clicked, or the Enter key is pressed inside a TextField.
  • Useful Methods:
    • String getActionCommand(): Returns the label/command text of the button clicked (e.g., "Submit").
    • Object getSource(): Returns the reference to the component that fired the event.

2. AdjustmentEvent

  • Generated whenever the user moves the slider thumb of a Scrollbar (up, down, page-up, or drag).
  • Useful Method: int getValue() — returns the current integer value of the scrollbar.

3. ContainerEvent

  • Generated when a component is dynamically added to (componentAdded) or removed from (componentRemoved) a Container (Panel or Frame) at runtime.
  • Useful Method: Component getChild() — returns the component that was added or removed.

4. FocusEvent

  • Generated when a component gains keyboard focus (focusGained, e.g., user clicks inside a TextField) or loses focus (focusLost, e.g., user presses Tab to move to the next field).

5. ItemEvent

  • Generated when a checkable or selectable item changes state—such as ticking/unticking a Checkbox, choosing an option from a Choice drop-down, or selecting an item in a List.
  • Useful Methods: Object getItem() (returns the selected item) and int getStateChange() (ItemEvent.SELECTED or ItemEvent.DESELECTED).

6. KeyEvent

  • Generated when keyboard input occurs on an active component.
  • Handled by KeyListener which has 3 methods: keyPressed(KeyEvent e), keyReleased(KeyEvent e), and keyTyped(KeyEvent e).
  • Useful Methods: char getKeyChar() (returns character typed, like 'A') and int getKeyCode() (returns virtual key code like KeyEvent.VK_ENTER).

7. MouseEvent

  • Generated when the user interacts with the mouse cursor. Handled by two interfaces:
    • MouseListener (5 methods): mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited().
    • MouseMotionListener (2 methods): mouseDragged(), mouseMoved().
  • Useful Methods: int getX(), int getY() (returns exact (x, y) pixel coordinates of the mouse click!) and int getClickCount().

8. TextEvent

  • Generated whenever a user types or deletes even a single character inside a TextField or TextArea.

9. WindowEvent

  • Generated when the state of a top-level Frame or Window changes.
  • Handled by WindowListener, which defines 7 abstract methods:
    1. windowOpened(WindowEvent e)
    2. windowClosing(WindowEvent e) (Triggered when user clicks the [X] close button!)
    3. windowClosed(WindowEvent e)
    4. windowIconified(WindowEvent e) (Minimized)
    5. windowDeiconified(WindowEvent e) (Restored)
    6. windowActivated(WindowEvent e)
    7. windowDeactivated(WindowEvent e)

3. Adapter Classes in Java (Why & How They Are Used)

This is a guaranteed 5- to 8-mark question in Unit 4 of DAVV BCA exams!

The Problem Without Adapter Classes:

Suppose you want to close an AWT Frame when the user clicks the [X] close button in the top-right corner. To do this, you only need 1 method: windowClosing(WindowEvent e). However, if your class implements the WindowListener interface, Java forces you to write empty {} bodies for all 7 methods of WindowListener! Writing 6 useless empty methods clutters your code.

The Solution: What is an Adapter Class?

An Adapter Class is an abstract convenience class in java.awt.event that provides default empty ({}) implementations for all methods of a multi-method Listener interface (any listener interface that has more than 1 method).

Instead of implementing the Listener interface (implements WindowListener), you simply extend the Adapter class (extends WindowAdapter) and override ONLY the single method you actually care about!

Figure 4.3: Implementing WindowListener vs Extending WindowAdapter
Without Adapter (implements WindowListener)
  • Must write all 7 methods!
  • windowClosing() (Actual code)
  • Plus 6 empty methods: windowOpened(){}, windowClosed(){}, windowIconified(){}, etc.
With Adapter (extends WindowAdapter)
  • WindowAdapter already provides empty bodies for all 7 methods
  • You override ONLY 1 method: windowClosing(WindowEvent e)!
  • Code is clean, short, and readable

List of Listener Interfaces and Their Corresponding Adapter Classes

(Note: Listener interfaces with only 1 method—like ActionListener, ItemListener, AdjustmentListener, TextListener—do NOT need or have an Adapter class!)

Multi-Method Listener Interface Number of Methods Corresponding Adapter Class
WindowListener 7 methods WindowAdapter
MouseListener 5 methods MouseAdapter
KeyListener 3 methods KeyAdapter
FocusListener 2 methods FocusAdapter
ContainerListener 2 methods ContainerAdapter
MouseMotionListener 2 methods MouseMotionAdapter

4. Complete Program Using WindowAdapter and MouseAdapter

import java.awt.*;
import java.awt.event.*;

public class AdapterClassDemo extends Frame {
    Label lblCoords;

    public AdapterClassDemo() {
        setTitle("Adapter Class Demo (Click Anywhere or Close [X])");
        setSize(400, 250);
        setLayout(new FlowLayout());

        lblCoords = new Label("Click anywhere inside the frame!");
        add(lblCoords);

        // 1. Using MouseAdapter: Override ONLY mouseClicked() out of 5 methods!
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                lblCoords.setText("Mouse Clicked at X=" + e.getX() + ", Y=" + e.getY());
            }
        });

        // 2. Using WindowAdapter: Override ONLY windowClosing() out of 7 methods!
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("Closing Frame Window...");
                dispose();       // Releases window resources
                System.exit(0);  // Terminates program
            }
        });

        setVisible(true);
    }

    public static void main(String[] args) {
        new AdapterClassDemo();
    }
}

💡 Exam Preparation Tips for DAVV BCA

  • Why doesn’t ActionListener have an ActionAdapter class? Because ActionListener has only 1 method (actionPerformed), so an adapter class is completely unnecessary! (Mentioning this in the exam shows deep conceptual clarity).
  • Always write the WindowAdapter example overriding windowClosing(WindowEvent e) when asked about Adapter Classes.