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

Event Classes (EventObject, ActionEvent, MouseEvent, KeyEvent) & Listener Interfaces

HIGH PRIORITY (Prep Guide)Official Syllabus~17 min study
Official KTU 2024 Syllabus Topics Covered Here
Event objects and event classesEvent listener interfacesActionListenerActionEventMouse and keyboard event conceptsJava event handling examples

1. Topic Introduction

What exact information does Java hand your listener when a button is clicked, a key is pressed, or a mouse is dragged? It hands you specialized Event Objects descending from java.util.EventObject and java.awt.AWTEvent. Knowing the major Event Classes, their methods, and their paired Listener Interfaces is essential for both theory questions and event-handling code writing.

2. Start From Zero: Specialized Incident Reports (Event Classes) & On-Duty Specialists (Listener Interfaces)

Different events carry different clues! A button press needs to tell you what command text was clicked (ActionEvent.getActionCommand()). A keyboard event needs to tell you which key/character was pressed (KeyEvent.getKeyChar(), getKeyCode()). A mouse click needs (X, Y) coordinates (MouseEvent.getX(), getY(), getClickCount()). Each specialized report goes only to the matching specialist interface (ActionListener, KeyListener, MouseListener)!

Key Takeaway: Root: java.util.EventObject (getSource()) -> java.awt.AWTEvent (getID()) -> specific events in java.awt.event.* (ActionEvent, ItemEvent, KeyEvent, MouseEvent, WindowEvent, etc.).

3. Essential Exam Definitions

java.util.EventObject
Root superclass of ALL event classes in Java, defining Object getSource() and toString().
java.awt.AWTEvent
Direct subclass of EventObject serving as the superclass for all AWT/Swing Delegation Event Model events (int getID()).
ActionEvent & ActionListener
Event fired when a JButton is pressed, a JTextField receives Enter, or a menu item is selected; handled by implementing void actionPerformed(ActionEvent ae).

4. Detailed Technical Explanation & Syntax

1. Essential Event Classes (java.awt.event)

Review the event classes covered in your lecture slides (especially their hierarchy and key methods):

  • ActionEvent: Generated by JButton, JTextField (Enter), menu items. Methods: getActionCommand(), getModifiers(), getWhen(). Constant: ACTION_PERFORMED.
  • ItemEvent: Generated by JCheckBox, JRadioButton, JToggleButton, JComboBox. Methods: getItem(), getItemSelectable(), getStateChange() (SELECTED/DESELECTED).
  • ComponentEvent -> Superclass (directly or indirectly) of ContainerEvent, FocusEvent, WindowEvent, and InputEvent (KeyEvent, MouseEvent).
  • KeyEvent (subclass of InputEvent): 3 constants KEY_PRESSED, KEY_RELEASED, KEY_TYPED. Methods: char getKeyChar(), int getKeyCode() (virtual key codes like VK_A, VK_UP; note KEY_TYPED returns VK_UNDEFINED for getKeyCode()!).
  • MouseEvent & MouseWheelEvent (subclass of InputEvent): Methods: getX(), getY(), getPoint(), getClickCount(), getButton(), getXOnScreen(), getYOnScreen(). MouseWheelEvent adds getWheelRotation() and getScrollType().
  • WindowEvent: Generated when window opens, closes, activates, or iconifies (getWindow(), getOppositeWindow()).
  • AdjustmentEvent (scrollbars) & TextEvent (AWT text changes).

2. Matching Listener Interfaces & Their Exact Method Signatures

Every listener interface in java.awt.event forces implementing classes to define ALL of its declared methods:

  • ActionListener (1 method): void actionPerformed(ActionEvent ae)
  • ItemListener (1 method): void itemStateChanged(ItemEvent ie)
  • KeyListener (3 methods): keyPressed(KeyEvent), keyReleased(KeyEvent), keyTyped(KeyEvent)
  • MouseListener (5 methods): mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased
  • MouseMotionListener (2 methods): mouseDragged(MouseEvent), mouseMoved(MouseEvent)
  • MouseWheelListener (1 method): mouseWheelMoved(MouseWheelEvent)
  • FocusListener (2 methods): focusGained(FocusEvent), focusLost(FocusEvent)
  • WindowListener (7 methods): windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, windowActivated, windowDeactivated

5. Working Principle: Why Mouse Events Split Between MouseListener and MouseMotionListener

  1. Mouse movement fires dozens of events per second; separating MouseMotionListener (mouseMoved, mouseDragged) from MouseListener (mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited) means a component wanting only clicks avoids receiving heavy mouse-motion overhead! (Also an application of ISP!).

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.

7. Complete Java Code Examples & Tracing

Handling Action, Mouse & Keyboard Events in SwingMouseKeyActionDemo.java
Complete Swing panel implementing ActionListener, MouseListener, and KeyListener with full method signatures ready for KTU exams.
1import javax.swing.*;
2import java.awt.*;
3import java.awt.event.*;
4
5public class MouseKeyActionDemo extends JFrame
6 implements ActionListener, MouseListener, KeyListener {
7
8 JLabel status = new JLabel("Interact with button or type keys...");
9 JTextField input = new JTextField(15);
10 JButton clearBtn = new JButton("Clear");
11
12 public MouseKeyActionDemo() {
13 super("Event Classes & Listeners Demo");
14 setLayout(new FlowLayout());
15
16 clearBtn.addActionListener(this);
17 clearBtn.addMouseListener(this);
18 input.addKeyListener(this);
19
20 add(new JLabel("Type:"));
21 add(input);
22 add(clearBtn);
23 add(status);
24
25 setSize(420, 160);
26 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 }
28
29 @Override
30 public void actionPerformed(ActionEvent ae) {
31 input.setText("");
32 status.setText("ActionEvent: Cleared via " + ae.getActionCommand());
33 }
34
35 @Override
36 public void keyPressed(KeyEvent ke) {
37 status.setText("KeyPressed code: " + ke.getKeyCode());
38 }
39
40 @Override public void keyTyped(KeyEvent ke) {
41 status.setText("KeyTyped char: " + ke.getKeyChar());
42 }
43 @Override public void keyReleased(KeyEvent ke) {}
44
45 @Override
46 public void mouseClicked(MouseEvent me) {
47 status.setText("Mouse clicked at (" + me.getX() + ", " + me.getY() + ")");
48 }
49
50 @Override public void mouseEntered(MouseEvent me) { status.setText("Mouse entered button"); }
51 @Override public void mouseExited(MouseEvent me) { status.setText("Mouse exited button"); }
52 @Override public void mousePressed(MouseEvent me) {}
53 @Override public void mouseReleased(MouseEvent me) {}
54
55 public static void main(String[] args) {
56 if (GraphicsEnvironment.isHeadless()) {
57 System.out.println("MouseKeyActionDemo compiled cleanly (headless environment).");
58 return;
59 }
60 SwingUtilities.invokeLater(() -> new MouseKeyActionDemo().setVisible(true));
61 }
62}
Expected Output
MouseKeyActionDemo compiled cleanly (headless environment).
Keywords:ActionEventActionListenerMouseEventMouseListenerKeyEventKeyListener
Common Exam & Coding Mistakes
  • Implementing MouseListener and forgetting 1 of its 5 methods (mouseEntered/mouseExited/mousePressed/mouseReleased/mouseClicked) -> compile error!
  • Confusing mouseMoved/mouseDragged (belonging to MouseMotionListener) with MouseListener.
  • Calling ke.getKeyCode() inside keyTyped expecting a virtual key code (always returns VK_UNDEFINED for KEY_TYPED!).

Comparison Tables

Major Event Sources, Event Classes & Listener Interfaces
User Action / SourceEvent ClassListener InterfaceMethod(s)
Click JButton / Enter in JTextFieldActionEventActionListeneractionPerformed(ActionEvent)
Toggle JCheckBox / JRadioButtonItemEventItemListeneritemStateChanged(ItemEvent)
Type or press keyboard keyKeyEventKeyListenerkeyPressed, keyReleased, keyTyped
Click / press / hover mouseMouseEventMouseListenermouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited
Move / drag mouseMouseEventMouseMotionListenermouseDragged, mouseMoved
Open / close / minimize JFrameWindowEventWindowListenerwindowOpened, windowClosing, windowClosed, etc. (7 methods)

Real-World Applications

  • Drawing apps combine MouseListener + MouseMotionListener (mousePressed + mouseDragged); games use KeyListener (VK_UP, VK_LEFT).

Important KTU Exam Points

  • Memorize the 5 MouseListener methods, 2 MouseMotionListener methods, 3 KeyListener methods, and 1 ActionListener method!
  • Always mention java.util.EventObject (getSource()) -> java.awt.AWTEvent (getID()) as the root hierarchy.

Memory Techniques & Revision

  • Listener Counts: Action=1, Item=1, MouseMotion=2, Key=3, Mouse=5, Window=7!

Common Pitfalls to Avoid

  • Writing public void actionPerformed() WITHOUT the (ActionEvent e) parameter (fails to override ActionListener!).

KTU-Style Questions & Exam-Ready Answers

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

Introduction: All AWT/Swing event objects extend java.awt.AWTEvent (subclass of java.util.EventObject) and are handled by matching listener interfaces in java.awt.event.

  • 1. ActionEvent -> ActionListener (actionPerformed): Fired by JButton clicks and JTextField Enter; provides getActionCommand().
  • 2. ItemEvent -> ItemListener (itemStateChanged): Fired by JCheckBox / JRadioButton; provides getItem() and getStateChange().
  • 3. KeyEvent -> KeyListener (keyPressed, keyReleased, keyTyped): Captures keyboard activity via getKeyChar() and getKeyCode().
  • 4. MouseEvent -> MouseListener (5 click/hover methods) & MouseMotionListener (mouseMoved, mouseDragged): Provides coordinates getX(), getY(), getClickCount().

Quick Understanding Check

1. Which listener interface handles mouseDragged(MouseEvent) and mouseMoved(MouseEvent)?