Event Classes (EventObject, ActionEvent, MouseEvent, KeyEvent) & Listener Interfaces
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.
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)!
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.EventObjectObject getSource() and toString().java.awt.AWTEventEventObject serving as the superclass for all AWT/Swing Delegation Event Model events (int getID()).ActionEvent & ActionListenerJButton 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 byJButton,JTextField(Enter), menu items. Methods:getActionCommand(),getModifiers(),getWhen(). Constant:ACTION_PERFORMED.ItemEvent: Generated byJCheckBox,JRadioButton,JToggleButton,JComboBox. Methods:getItem(),getItemSelectable(),getStateChange()(SELECTED/DESELECTED).ComponentEvent-> Superclass (directly or indirectly) ofContainerEvent,FocusEvent,WindowEvent, andInputEvent(KeyEvent,MouseEvent).KeyEvent(subclass ofInputEvent): 3 constantsKEY_PRESSED,KEY_RELEASED,KEY_TYPED. Methods:char getKeyChar(),int getKeyCode()(virtual key codes likeVK_A,VK_UP; noteKEY_TYPEDreturnsVK_UNDEFINEDforgetKeyCode()!).MouseEvent&MouseWheelEvent(subclass ofInputEvent): Methods:getX(),getY(),getPoint(),getClickCount(),getButton(),getXOnScreen(),getYOnScreen().MouseWheelEventaddsgetWheelRotation()andgetScrollType().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,mouseReleasedMouseMotionListener(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
- Mouse movement fires dozens of events per second; separating
MouseMotionListener(mouseMoved,mouseDragged) fromMouseListener(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
Delegation Event Model
Core interaction diagram of Java's Delegation Event Model showing Event Source registration, Event Object generation, and selective notification to registered Listeners.
- Event Source: UI component generating an event (
JButton,JTextField) withaddXListener(). - Event Object: Object encapsulating state change (
ActionEvent,MouseEvent) rooted atjava.util.EventObject. - Event Listener: Object implementing listener interface (
ActionListener) registered to receive notifications.
- Step 1 (Setup): Listener registers with Source via
source.addActionListener(listener). - Step 2 (Trigger): User clicks button; Source creates an
ActionEventobject. - Step 3 (Dispatch): Source invokes
listener.actionPerformed(event)on every registered listener (multicasting). - Step 4 (Handle): Listener executes application logic and returns.
- Draw two main boxes:
Event Source (e.g. JButton)andEvent Listener (implements ActionListener). - Arrow 1 (Setup): Listener ---> Source labeled
1. Register (addActionListener). - Arrow 2 (Event): User action ---> Source ---> creates
Event Object (ActionEvent)---> invokesactionPerformed(e)on Listener.
7. Complete Java Code Examples & Tracing
ActionListener, MouseListener, and KeyListener with full method signatures ready for KTU exams.| 1 | import javax.swing.*; |
| 2 | import java.awt.*; |
| 3 | import java.awt.event.*; |
| 4 | |
| 5 | public 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 | } |
MouseKeyActionDemo compiled cleanly (headless environment).
ActionEventActionListenerMouseEventMouseListenerKeyEventKeyListener- Implementing
MouseListenerand forgetting 1 of its 5 methods (mouseEntered/mouseExited/mousePressed/mouseReleased/mouseClicked) -> compile error! - Confusing
mouseMoved/mouseDragged(belonging toMouseMotionListener) withMouseListener. - Calling
ke.getKeyCode()insidekeyTypedexpecting a virtual key code (always returnsVK_UNDEFINEDforKEY_TYPED!).
Comparison Tables
| User Action / Source | Event Class | Listener Interface | Method(s) |
|---|---|---|---|
Click JButton / Enter in JTextField | ActionEvent | ActionListener | actionPerformed(ActionEvent) |
Toggle JCheckBox / JRadioButton | ItemEvent | ItemListener | itemStateChanged(ItemEvent) |
| Type or press keyboard key | KeyEvent | KeyListener | keyPressed, keyReleased, keyTyped |
| Click / press / hover mouse | MouseEvent | MouseListener | mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited |
| Move / drag mouse | MouseEvent | MouseMotionListener | mouseDragged, mouseMoved |
Open / close / minimize JFrame | WindowEvent | WindowListener | windowOpened, windowClosing, windowClosed, etc. (7 methods) |
Real-World Applications
- Drawing apps combine
MouseListener+MouseMotionListener(mousePressed+mouseDragged); games useKeyListener(VK_UP,VK_LEFT).
Important KTU Exam Points
- Memorize the 5
MouseListenermethods, 2MouseMotionListenermethods, 3KeyListenermethods, and 1ActionListenermethod! - 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 overrideActionListener!).
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 byJButtonclicks andJTextFieldEnter; providesgetActionCommand(). - 2. ItemEvent -> ItemListener (
itemStateChanged): Fired byJCheckBox/JRadioButton; providesgetItem()andgetStateChange(). - 3. KeyEvent -> KeyListener (
keyPressed,keyReleased,keyTyped): Captures keyboard activity viagetKeyChar()andgetKeyCode(). - 4. MouseEvent -> MouseListener (5 click/hover methods) & MouseMotionListener (
mouseMoved,mouseDragged): Provides coordinatesgetX(),getY(),getClickCount().
Quick Understanding Check
1. Which listener interface handles mouseDragged(MouseEvent) and mouseMoved(MouseEvent)?