Event Handling
Event, Event Source, and Event Listener
In graphical user interface (GUI) programming, events are how a program responds to user interactions.
The core components are:
Event Source: Is the GUI component that generates an event.
JButton
is the source of a button click event,JTextField
is the source of a key press event.Event: Is an object that represents some action that has occurred and contains information about what happened and where it happened. This could be a user clicking a button, moving the mouse, pressing a key, or a system action like a timer going off.
Event Listener: Is an object that "listens" for events and processes them when they occur. To receive notifications, a listener must be registered with an event source. It contains the code that defines what should happen in response to an event.
The Delegation Event Model
The delegation event model is the mechanism Java uses to handle events in GUI applications. It's called the "delegation" model because the responsibility of handling an event is delegated from the source (the component) to a separate listener object.
This model is composed of the three components (event, event source and event listener) and works in a simple, three-step process:
Registration: A listener object must first register itself with a source object. This tells the source, "if a certain type of event happens to you, notify me."
ActionListener
object registers with aJButton
using thebutton.addActionListener(myListener)
method.Notification (Firing an Event): When a user interacts with the source (e.g., clicks the button), the source creates an event object that describes the action.
Delegation and Response: The source then "fires" or sends this event object to all of its registered listeners by calling a specific method on them (e.g.,
actionPerformed(eventObject)
). The listener's method contains the code that executes in response to the event.
This separation keeps the user interface logic (the look of the button) separate from the application logic (what the button does).
Adapter Classes
An Adapter Class are a simple, pre-built classes that provide empty implementation of an event listener interface. Extending the adapter class allows for overriding only the methods that are being used instead of overriding all methods in the interface.
Example: For complex listeners, like MouseListener
or KeyListener
, the interface defines multiple methods (e.g., MouseListener
has mousePressed
, mouseReleased
, mouseClicked
, mouseEntered
, and mouseExited
).
To use only, mouseClicked
in the MouseListener
interface empty bodies must be provided for the other four methods that are not needed. This creates unnecessary boilerplate code.
Instead of this:
class MyMouseHandler implements MouseListener {
public void mouseClicked(MouseEvent e) { /* Handling code here */ }
public void mousePressed(MouseEvent e) {} // Empty
public void mouseReleased(MouseEvent e) {} // Empty
public void mouseEntered(MouseEvent e) {} // Empty
public void mouseExited(MouseEvent e) {} // Empty
}
Using Adapter class makes it much cleaner:
import java.awt.event.MouseAdapter;
class MyMouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
// My code here. No other empty methods needed!
}
}
Handling Keyboard Events
Creating a window that listens for keyboard input. Uses KeyListener
interface to detect when a key is typed, pressed down, or released, and it displays the status of these actions.
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class KeyAdapterDemo extends JFrame {
private JLabel statusLabel;
public KeyAdapterDemo() {
// --- 1. Frame Setup ---
setSize(400, 200);
setTitle("Key Adapter Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// --- 2. Component Setup ---
statusLabel = new JLabel("Press any key...");
add(statusLabel);
// --- 3. Add the Key Listener using an Adapter Class ---
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
statusLabel.setText("Key Typed: "
+ e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
statusLabel.setText("Key Pressed: "
+ KeyEvent.getKeyText(keyCode));
}
});
// --- 4. Make the frame visible ---
setVisible(true);
}
public static void main(String[] args) {
new KeyAdapterDemo();
}
}
Handling Mouse Events
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class MouseAdapterDemo extends JFrame {
JLabel statusLabel;
public MouseAdapterDemo() {
// --- 1. Frame Setup ---
setLayout(new FlowLayout());
setSize(400, 200);
setTitle("Swing Adapter Class Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// --- 2. Component Setup ---
statusLabel = new JLabel("No event yet.");
add(statusLabel);
// --- 3. Add the Mouse Listener ---
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
statusLabel.setText("Mouse clicked at: ("
+ me.getX() + ", " + me.getY() + ")");
}
@Override
public void mouseEntered(MouseEvent me) {
statusLabel.setText("Mouse entered the window.");
}
@Override
public void mouseExited(MouseEvent me) {
statusLabel.setText("Mouse left the window.");
}
});
// --- 4. Make the frame visible ---
setVisible(true);
}
public static void main(String[] args) {
new MouseAdapterDemo();
}
}