KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 3: Event Handling in Swing

Event Handling Mechanisms & the Delegation Event Model

HIGH PRIORITY (Prep Guide)Official Syllabus~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to event handlingEvent handling mechanismsDelegation Event ModelEvent sourcesEvent registrationEvent handling sequence

1. Topic Introduction

Desktop GUIs are event-driven: unlike console programs that read line 1 then exit, a Swing window sits calmly waiting until a user clicks a button, types a key, or moves the mouse. In modern Java (JDK 1.1 onward), all AWT and Swing events follow the Delegation Event Model—one of the highest-yield 6-mark and 9-mark diagram questions in Module 4.

2. Start From Zero: Subscribing to YouTube Notifications (Delegation) vs Passing Flyers Up a Chain (Old Java 1.0)

In ancient Java 1.0, an event travelled blindly up every parent container (Button -> Panel -> Frame) whether anyone cared or not—wasting CPU! Modern Java's Delegation Event Model works like subscribing to a channel: ONLY listeners who explicitly clicked 'Subscribe' (**addActionListener(listener)) on a specific Event Source** (JButton) receive an **Event Notification (ActionEvent)** when clicked. Zero wasted notifications, and UI widgets stay completely separate from business logic!

Key Takeaway: Delegation Event Model has 3 pillars: (1) Event Source (creates event), (2) Event Object (describes state change), and (3) Event Listener (registered interface object that receives & handles notifications).

3. Essential Exam Definitions

Event
An object describing a state change in a source (caused by GUI user actions like button clicks/keystrokes, or non-UI triggers like timers/counters).
Event Source
An object (such as JButton, JTextField, JFrame) that generates an event and dispatches it to registered listeners via addTypeListener(TypeListener el) and removeTypeListener(...).
Event Listener
An object implementing one or more listener interfaces (from java.awt.event or javax.swing.event) that registers with a source to receive and handle event notifications.
Multicasting vs Unicasting Events
Multicasting notifies ALL registered listeners when an event fires (standard in Java); Unicasting allows at most one registered listener (throwing java.util.TooManyListenersException on a second registration).

4. Detailed Technical Explanation & Syntax

1. Two-Step Delegation Workflow & Advantages

To handle events using the Delegation Event Model, perform two steps: (1) Implement the appropriate listener interface (implements ActionListener) in your handler class (or anonymous/lambda class); (2) Register that listener instance with the source (btn.addActionListener(this);).

Key Advantage (Separation of Concerns): Application logic that processes events is cleanly separated from the UI logic that generates those events, eliminating Java 1.0's containment-hierarchy overhead.

Multiple Events Rule: A single source can generate multiple event types (e.g., JButton fires ActionEvent, MouseEvent, FocusEvent)—each must be registered separately (addActionListener, addMouseListener).

5. Working Principle: Step-by-Step Event Handling Sequence on EDT

  1. 1. GUI initializes on Swing's Event Dispatching Thread (EDT) via SwingUtilities.invokeLater.
  2. 2. Application registers listener(s) with source: source.addActionListener(listener).
  3. 3. User interacts with source (clicks JButton).
  4. 4. Source constructs an Event Object (ActionEvent) storing reference to source and command string.
  5. 5. On EDT, source invokes listener.actionPerformed(event) on every registered listener (multicast); listener updates UI and returns.

6. Examination-Ready Diagrams

Diagram 16

Delegation Event Model

User ActionClick / KeypressEvent Sourcee.g., JButton (addActionListener)Event ObjectActionEvent (src, cmd)Event Listenerimplements ActionListenerStep 1: Register Listener (source.addActionListener(listener))

Core interaction diagram of Java's Delegation Event Model showing Event Source registration, Event Object generation, and selective notification to registered Listeners.

Key Components
  • Event Source: UI component generating an event (JButton, JTextField) with addXListener().
  • Event Object: Object encapsulating state change (ActionEvent, MouseEvent) rooted at java.util.EventObject.
  • Event Listener: Object implementing listener interface (ActionListener) registered to receive notifications.
Step-by-Step Flow
  1. Step 1 (Setup): Listener registers with Source via source.addActionListener(listener).
  2. Step 2 (Trigger): User clicks button; Source creates an ActionEvent object.
  3. Step 3 (Dispatch): Source invokes listener.actionPerformed(event) on every registered listener (multicasting).
  4. Step 4 (Handle): Listener executes application logic and returns.
How to Draw in KTU Exam
  • Draw two main boxes: Event Source (e.g. JButton) and Event Listener (implements ActionListener).
  • Arrow 1 (Setup): Listener ---> Source labeled 1. Register (addActionListener).
  • Arrow 2 (Event): User action ---> Source ---> creates Event Object (ActionEvent) ---> invokes actionPerformed(e) on Listener.
Diagram 17

Swing Event Handling Sequence on EDT

1. main() ThreadSwingUtilities.invokeLater()2. Event Dispatch ThreadCreates JFrame & reads Queue3. Source -> EventFires ActionEvent on click4. Listener RunsUpdates UI safely on EDTAll Swing creation & event handlers execute on the single Event Dispatching Thread (EDT)

End-to-end runtime sequence showing how Swing initializes UI on the Event Dispatching Thread (EDT) and dispatches OS user input through the event queue to listener callbacks.

Key Components
  • Main Thread: Schedules GUI startup via SwingUtilities.invokeLater(...).
  • Event Dispatching Thread (EDT): Single dedicated thread handling UI creation, painting, and all event callbacks safely.
  • Event Queue: Buffers OS clicks/keystrokes into Java EventObject tasks.
  • Registered Listener: Executes actionPerformed() / itemStateChanged() on the EDT.
Step-by-Step Flow
  1. main() calls SwingUtilities.invokeLater(...) to construct JFrame safely on EDT.
  2. User clicks a Swing control -> OS input enters AWT/Swing Event Queue.
  3. EDT pops event -> wraps as ActionEvent -> notifies registered ActionListener.
  4. Listener updates JLabel/JTextField on EDT -> Swing repaints screen.
How to Draw in KTU Exam
  • Draw 4 vertical lifelines or horizontal stages: main() Thread -> SwingUtilities.invokeLater() -> Event Dispatching Thread (EDT) + Event Queue -> Source Component -> Listener.actionPerformed() -> UI Repaint.

7. Complete Java Code Examples & Tracing

Delegation Event Model with Multicasting & RegistrationDelegationEventDemo.java
Demonstrates registering TWO separate ActionListeners onto one JButton source (multicasting) and triggering/verifying event dispatch cleanly.
1import javax.swing.*;
2import java.awt.event.*;
3
4public class DelegationEventDemo {
5 public static void main(String[] args) {
6 // 1. Event Source
7 JButton submitBtn = new JButton("Save Exam Form");
8
9 // 2. Register First Listener (Multicasting demo)
10 submitBtn.addActionListener(new ActionListener() {
11 @Override
12 public void actionPerformed(ActionEvent e) {
13 System.out.println("Listener 1 -> Command: " + e.getActionCommand());
14 }
15 });
16
17 // 3. Register Second Listener on the same Source
18 submitBtn.addActionListener(e ->
19 System.out.println("Listener 2 -> Audit log recorded from: " + e.getSource().getClass().getSimpleName())
20 );
21
22 // Programmatic click simulation demonstrates delegation without requiring display!
23 submitBtn.doClick();
24 }
25}
Expected Output
Listener 2 -> Audit log recorded from: JButton
Listener 1 -> Command: Save Exam Form
Keywords:ActionListenerActionEventaddActionListeneractionPerformed
Common Exam & Coding Mistakes
  • Implementing ActionListener in a class but forgetting to call btn.addActionListener(this); (clicking the button does nothing!).
  • Thinking Swing events execute on main() thread—they run on the Event Dispatching Thread (EDT).

Real-World Applications

  • Every Swing button click, menu selection, keyboard shortcut, and mouse drag relies on the Delegation Event Model.

Important KTU Exam Points

  • Always draw Diagram 16 (Source <-> Event Object <-> Listener + Registration arrow) whenever asked about Delegation Event Model!
  • Explicitly explain Multicasting vs Unicasting (TooManyListenersException) and the 2 benefits over Java 1.0 propagation.

Memory Techniques & Revision

  • Delegation 3S — 'Source generates, Signal (EventObject) carries, Subscriber (Listener) handles'.

Common Pitfalls to Avoid

  • Confusing Event Source (JButton) with Event Object (ActionEvent).

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: The Delegation Event Model is Java's modern event-handling mechanism where a source generates an event object and dispatches it directly to one or more registered listener objects.

  • Components: (1) Event Object (EventObject / AWTEvent) representing a state change; (2) Event Source generating events and managing registration via addTypeListener() / removeTypeListener(); (3) Event Listener implementing listener interfaces (ActionListener, MouseListener) to process notifications.
  • Working: Listener registers with source -> User triggers event -> Source creates Event Object -> Source multicasts event by calling listener's callback method (actionPerformed(ae)).
  • Advantages: Clean separation of UI logic from business/event-processing logic, and eliminates the overhead of propagating unhandled events up the containment hierarchy.
Exam Diagram Note: Reproduce Diagram 16 (Delegation Event Model) with clear registration and dispatch arrows.

Quick Understanding Check

1. What does 'multicasting' mean in Java's Delegation Event Model?