3 Event Handling

Advanced Java Programming · Unit 3 · 4 hrs

Event Handling

Exam-focused notes for Event Handling (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

Event Handling in short

This unit explains how a Swing or AWT program reacts to user actions such as clicks and key presses, through the delegation event model, its listener interfaces, and the adapter classes that make listeners easier to write.

Event Handling: notes

Event Handling Concept, Listener Interfaces, Using Action Commands, Adapter Classes

An event represents a change of state, produced by an action such as a button click, a key press, a mouse movement, or the completion of some background operation. Events fall into two categories: foreground events, which need direct user interaction to occur (clicking a button, moving the cursor), and background events, which do not (an operating system interrupt, the completion of an operation started earlier).

Java handles events through the delegation event model. Under this model, a source (a button, a checkbox, a menu item, and so on) generates an event, and a separate listener object, implementing the appropriate listener interface, is registered with that source to receive and react to the event. Registration always follows the same pattern, addXxxListener(), where Xxx names the kind of event: addActionListener() for ActionEvent, addKeyListener() for KeyEvent, and so forth.

Event classListener interface
ActionEventActionListener
MouseEventMouseListener, MouseMotionListener
MouseWheelEventMouseWheelListener
KeyEventKeyListener
ItemEventItemListener
TextEventTextListener
WindowEventWindowListener
ComponentEventComponentListener
FocusEventFocusListener

Different components support different registration methods depending on which events they can generate: a Button or MenuItem accepts addActionListener(); a Checkbox or Choice accepts addItemListener(); a TextField accepts both addActionListener() (fired on Enter) and addTextListener() (fired on every edit); a TextArea accepts addTextListener(); a List accepts both addActionListener() and addItemListener().

Action commands give an ActionEvent a stable, human-readable identifier that does not depend on the exact wording of a button's label. AbstractButton.setActionCommand(String) sets it, and inside the listener, event.getActionCommand() retrieves it, which is especially useful when several buttons share one ActionListener and the handler needs to tell them apart without comparing button labels or object references directly.

What this unit covers

  • Event Handling Concept, Listener Interfaces, Using Action Commands, Adapter Classes
  • Handling Action Events, Key Events, Focus Events, Mouse Event, Window Event, Item Events

Handling Action Events, Key Events, Focus Events, Mouse Event, Window Event, Item Events

2081 · 5 marks

Describe any two types of events. [5]

In Java, an event is an object that describes a state change in a source. Events are generated when a user interacts with GUI components such as clicking a button, pressing a key, moving the mouse, etc. Java uses the Delegation Event Model to handle events. --- Mouse events are generated when the...

Open this answer on its own page →

2079 · 5 marks

Why do we need event handling? Explain the use of action event with example. [5]

Event handling is needed in Java to make Graphical User Interface (GUI) applications interactive and responsive. Without event handling, a GUI program would simply display components (buttons, text fields, etc.) but would not respond to any user actions. Key reasons we need event handling: - To r...

Open this answer on its own page →

2076 · 10 marks

Write a Java program to find the sum of two numbers using swing components. Use text fields for input and output. Your program displays output if you press any key in keyboard. Use key adapter to handle events.[10]

This program uses Swing components (JTextField, JLabel, JFrame) for GUI and a KeyAdapter to handle keyboard events. Whenever the user presses any key in either input field, the sum is automatically calculated and displayed in the output text field. Note: The key difference from the button-based v...

Open this answer on its own page →

Event Handling Concept, Listener Interfaces, Using Action Commands, Adapter Classes

2078 · 5 marks

How can we use listener interface to handle events? Compare listener interface with adapter class. [5]

A listener interface is a predefined interface in Java (in java.awt.event package) that contains abstract methods corresponding to specific events. To handle events using a listener interface, the following steps are followed: Step 1: Implement the listener interface The class must implement the ...

Open this answer on its own page →

2077 · 5 marks

Define event delegation model. Why do we need adapter class in event handling? [5]

Show solved answer

Event Delegation Model and Adapter Classes in Java

Event Delegation Model (2 marks)

The Event Delegation Model is the standard event handling mechanism used in Java AWT and Swing. In this model, the task of handling an event is delegated from the source (component that generates the event) to a separate object called the listener (or handler).

Key Components:

ComponentRole
Event SourceThe UI component that generates the event (e.g., Button, TextField)
Event ObjectEncapsulates information about the event (e.g., ActionEvent, KeyEvent)
Event ListenerThe object that receives and handles the event

How it Works:

User Action --> Event Source --> Event Object --> Event Listener --> Handler Method
(e.g., click)  (Button)        (ActionEvent)    (ActionListener)  (actionPerformed())

Steps in Event Delegation:

  1. Implement the appropriate listener interface (e.g., ActionListener, KeyListener)
  2. Register the listener with the source using addXxxListener(this)
  3. Override the required handler method(s)

Example (from notes):

class AEvent extends Frame implements ActionListener {
    Button b = new Button("click me");
    b.addActionListener(this);  // Step 2: Register listener

    public void actionPerformed(ActionEvent e) {  // Step 3: Handle event
        tf.setText("Welcome");
    }
}

Why We Need Adapter Classes (3 marks)

The Problem:

Some listener interfaces in Java contain multiple abstract methods that must ALL be overridden when implementing the interface, even if we only need one or two of them.

For example, KeyListener has 3 methods:

  • keyPressed(KeyEvent e)
  • keyReleased(KeyEvent e)
  • keyTyped(KeyEvent e)

If we implement KeyListener directly, we are forced to provide the body of all 3 methods, even if we only care about keyPressed. This leads to unnecessary, cluttered code:

// Without Adapter - must override ALL methods (messy)
class MyClass extends Frame implements KeyListener {
    public void keyPressed(KeyEvent e)  { /* actual code */ }
    public void keyReleased(KeyEvent e) { /* empty - not needed */ }
    public void keyTyped(KeyEvent e)    { /* empty - not needed */ }
}

The Solution - Adapter Classes:

An Adapter class is a pre-built class that implements a listener interface with empty method bodies. We simply extend the adapter class and override only the methods we need.

// With Adapter - override ONLY what is needed (clean)
class KeyChecker extends KeyAdapter {
    @Override
    public void keyPressed(KeyEvent e) {
        // only this method is needed
    }
    // No need to write keyReleased() or keyTyped()
}

MouseAdapter Example (from notes):

public class MouseAdapterExample extends MouseAdapter {
    // Only mouseClicked() is overridden - no other methods needed
    public void mouseClicked(MouseEvent e) {
        Graphics g = f.getGraphics();
        g.setColor(Color.BLUE);
        g.fillOval(e.getX(), e.getY(), 30, 30);
    }
}

Common Adapter Classes:

Adapter ClassCorresponding Listener Interface
KeyAdapterKeyListener
MouseAdapterMouseListener
WindowAdapterWindowListener
FocusAdapterFocusListener

Summary:

Adapter classes reduce code complexity by providing default (empty) implementations of all methods in a listener interface, allowing the programmer to override only the required methods.

Open this answer on its own page →