Event-Driven Programming Procedural programming is executed in procedural order.
In event-driven programming, code is executed upon activation of events.
The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events.
The Delegation Event Model The concept is quite simple: a source generates an
event and sends it to one or more listeners. The listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
Listener must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.
The Delegation Event Model The advantage of this design is that the application
logic that processes events is separated from the user interface logic that generates those events.
A user interface element is able to "delegate" the processing of an event to a separate piece of code.
Events In the delegation model, an event is an object that
describes a state change in a source. An event can be defined as a type of signal to the program that something has happened.
The event is an object generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer.
The GUI component on which an event is
generated is called the source event.
Event ClassesThe root class of all event classes is java.util.EventObj. The subclasses of EventObj deal with special types of events, such as button actions, window events, component events, mouse events, and keystrokes.
User Actions, Source Object, and Event TypeSource Event Type
User Action Object Generated
Clicked a button JButton ActionEvent
Changed text JTextComponent TextEvent
Double-clicked on a list item JList ActionEvent
Selected or deselected an item JList ItemEvent with a single click
Selected or deselected an item JComboBox ItemEventMouse moved or dragged Component MouseEventMouse pressed, released, clicked, entered, or exited Component MouseEvent Window opened, closediconified, deiconified, closed Window WindowEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent,
. . . ActionEvent
Event Registration, Listening, and Handling
Handling Action EventsA listener has two major requirements: It must have been registered with one or more sources
to receive notifications about specific types of events. It must implement methods to receive and process
these notifications.
Handling Action Events A listener object must implement the corresponding listener
interface.
For example: A listener for a JButton must implement the
ActionListener interface. The actionListener
interface contains the actionPerformed(ActionEvent e)
method (handler).
An event object is passed to the handling method. You can get
useful data values from the event object for processing the event.
Use e.getSource() to obtain the source object in order to
determine whether it is a button, a check box, a menu item, etc.
Selected Event Handlers
Event Class Listener Interface Listener Methods (Handlers)
ActionEventActionEvent ActionListenerActionListener actionPerformed(ActionEvent e)actionPerformed(ActionEvent e)
ItemEvent ItemListener itemStateChanged(ItemEvent e)
WindowEvent WindowListener windowClosing(WindowEvent e)windowOpened(WindowEvent e)
ContainerEvent ContainerListener componentAdded(ContainerEvent e)componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent e)mouseReleased(MouseEvent e)
MouseMotionListener mouseDraged(MouseEvent e) mouseMoved(MouseEvent e)
KeyEvent KeyListener keyPressed(KeyEvent e)keyReleased(KeyEvent e)keyTyped(KeyEvent e)
TexEvent TextListener TextValueCnanged(TextEvent e)
Example: Handling Simple Action Events
Objective: Display two buttons in the window.
A message is displayed on the console to indicate which
button is clicked, when a button is clicked.
1. Create source of events (two buttons); 2. Add the buttons to the frame;
3. Register listeners to the buttons;
4. Implement (override) handler for the listener.
1. Handling Action Events: Source creationimport javx.swing.*;
import awt.*;
import java.awt.event.*;
public class TestActionEvent extends Jframe
implements ActionListener {
// 1st step: Create sources of eventssources of events (two buttons)
private JButton jbtOK = new Jbutton(“OK”);
private JButton jbtCL = new Jbutton(“Cancel”);
2. Handling Action Events: Registration // Constructor
public TestActionEvent () {
setTitle();
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
// 2nd step: Add the sources (buttons) to the frame
cp.add(jbtOK);
cp.add(jbtCL);
// 3rd step: Register listeners to the sources;
jbtOK.addActionListener(this);
jbtCL.addActionListener(this);
}
3. Handling Action Events// 4th step:implement handler
public void actionPerformed(ActionEvent e) {
if(e.getSource() == jbtOK) {
System.out.println(“The OK button is clicked”);
}
if(e.getSource() == jbtCL) {
System.out.println(“The Cancel button is clicked“);
}// actionPerformed
}
4. Handling Action Events: Test public static void main(String[] args) {
TestActionEvent frame = new TestActionEvent();
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
frame.setVisible(true);
}//main
}// class
Handling Action Events: Another Examplepublic class Button2Demo extends JFrame
{
private JButton jbtOK, jbtCL;
ActionListener handler = new ButtonHandler();
public Button2Demo() {
jbtOK = new JButton(“OK”);
jbtOK.addActionListener(handler);
jbtCL = new JButton(“Cancel”);
jbtCL.addActionListener(handler);
}
...
2. Handling Action Events ...
// Inner class
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbtOK) {
System.out.println(“The OK button is pressed”);
}//if
if(e.getSource() == jbtCL) {
System.out.println(“The Cancel button is
pressed”);
} //if
}// actionPerformed()
}// Inner class
}// public class
Example: Palindrome Demo
1. Declare UI Componentsimport Palindrome; // Import class Palindrome
class PalindromeDemo extends JFrame {
// Three Buttons
private JButton jbtClear, jbtCheck, jbtExit;
// One Text Field for input
private JTextField jtfString;
// Labels for result and instruction
private JLabel jlResult, jlInstr;
// One action listener for the buttons
ActionListener handler = new ButtonHandler();
2. Create UI Componentspublic PalindromeDemo() {
// Three Buttons jbtCheck = new JButton(“Check”); jbtClear = new JButton(“Clear”); jbtExit = new JButton(“Exit”); // One Text Field for input jtfString = new JTextField(32); // Labels for instruction and result jlInstr = new JLabel(“Enter phrase to be tested:”); jlResult = new JLabel(“”);
...
3. Add UI and Register Listener
4a. Implement Handler as Inner Classclass ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == jbtClear) { jtfString.setText(“”); jlResult.setText(“”); }//if if(e.getSource() == jbtCheck) { String str = jtfString.getText(); Palindrome pal = new Palindreme(str); boolean result = pal.IsPalindrome(); if(result) jlResult.setText(“Yes”); else jlResult.setText(“No”); } //if if(e.getSource() == jbtExit) { System.exit(0); } }// actionPerformed()}// inner class ButtonHandler
Use method of the class Palindrome to check the phrase.
4b. Implement Handler as Inner Class
5. Main method in the application public static void main(String[] args) {
String title = “Is it Palindrome?”;
// Create the frame with UI as an object of
// PalindromeDemo Class.
PalindromeDemo frame = new PalindromeDemo(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setsize(400,150);
frame.setVisible(true);
}//main
Handler events with Anonymous Class// Another way to implement handlers
private JButton jbtCheck = new JButton(”Check");
jbtCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = jtfString.getText();
boolean result = isPalindrome(str)
if(result == TRUE)
jlResult.setText(”Yes");
else
jlResult.setText(”No");
}
});
2. Another way to handle eventsprivate JButton jbtClear = new JButton(”Clear");
jbtClear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
jtfString.setText("");
jlResult.setText("");
}
});
3. Another way to handle eventsprivate JButton jbtExit = new JButton(”Exit");
jbtExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});