GUI - Event Handling
GUI - Event Handling
Introduction
Using a layout manager to arrange components
within a container may result in a GUI that looks
good, but in order to make it do anything ( for
example to get user input), you have to handle
events.
An event typically signifies an action by the user,
such as striking a key or clicking the mouse over a
JButton component.
But it can also refer to any other action performed by
the user or the program.
For example, an event can be generated when the
value of component's property changes or when a
specified amount of time elapses.
In the event handling process, there are three
2 important players : Event, Event Source, and
Event Listener (or Handler)
Event and Event Source
An event can be defined as a type of signal
to the program that something has
happened.
4
Event Classes
5
Event and Event Source…..
An event is created when an event occurs (i.e.,
user interacts with a GUI component).
An event is an instance (object) of an event
class.
Example
A button is the source object for a button-
clicking action event.(i.e. an ActionEvent Object
6 is generated. )
Event and Event Source ….
7
User Action, Source Object, and
Event Type
Source Event Type
User Action Object Generated
8
Event Classes…
9
Listeners, Registrations, and
Handling Events
Java uses Event-Delegation Model for
event handling: a source object fires an
event, and an object interested in the
event handles the event.
15
Listeners, Registrations, and
Handling Events…
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
frame.setSize(200, 200);
frame.setVisible(true);
}// End of main() method
}//end of class SimpleEventDemo
17
Listeners, Registrations, and
Handling Events…
public static void main (String arg[]){
MyEvent event = new MyEvent();
}
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent
evt) {
JButton source =
(JButton)evt.getSource();
source.setText("Button Has Been
Clicked, ...!");
}
}
18
Listeners, Registrations, and
Handling Events…
• Since JButton object fires ActionEvent, a Listener
object for ActionEvent must be an instance of
ActionListener,
so the listener class implements
ActionListener.
• The source object invoke addActionListener(listener)
to register a listener, as follows:
OKListener listener = new OKListener();
jbtOK.addActionListener(listener);
java.util.EventObject
+getSource(): Object Returns the object on which the event initially occurred.
java.awt.event.AWTEvent
java.awt.event.ActionEvent
+getActionCommand(): String Returns the command string associated with this action. For a
button, its text is the command string.
+getModifiers(): int Returns the modifier keys held down during this action event.
+getWhen(): long Returns the timestamp when this event occurred. The time is
the number of milliseconds since January 1, 1970, 00:00:00
GMT.
20
Event-listeners
ActionListener Method
Contains exactly one method
21
Event-listeners…
MouseListener Methods
22
Event-listeners…
MouseMotionListener Methods
23
Event-listeners…
WindowListener Methods
24
Event-listeners…
Other Listeners are
KeyListener
Methods
keyPressed(KeyEvent e) - Invoked when a key has been
pressed.
keyReleased(KeyEvent e) - Invoked when a key has
been released.
keyTyped(KeyEvent e) - Invoked when a key has been
typed.
FocusListeners
Methods
focusGained(FocusEvent e) - Invoked when a
component gains the keyboard focus.
focusLost(FocusEvent e) - Invoked when a component
loses the keyboard focus.
ItemListeners
Method
itemStateChanged(ItemEvent e) - Invoked when an item
25 has been selected or deselected by the user
Event-listeners…
TextListner
Method
textValueChanged(TextEvent e) - Invoked when the
value of the text has changed.
ContainerListner
Methods –
componentAdded(ContainerEvent e) - Invoked when
a component has been added to the container.
componentRemoved(ContainerEvent e) - Invoked
when a component has been removed from the
container.
AdjustmentListner
Methods
adjustmentValueChanged(AdjustmentEvent e) -
Invoked when the value of the adjustable has
changed.
26
Event-listeners…
More Listeners
ComponentListner
AWTEventListener
HierarchyBoundsListener
HierarchyListener
InputMethodListener
WindowFocusListener
WindowStateListener
27
Sources-events-listeners
Source Event object Listener Methods
<state change> (argument:
corresponding
event)
Mouse MouseEvent MouseListener mouseClicked
<mouse clicked, mousePressed
pressed, dragged, mouseReleased
moved/ entered, etc
exited a component MouseMotionList
etc> ener mouseDragged
mouseMoved
mouseWheelMo
MouseWheelList
MouseWheelEven ener
ved
t <page-up and
down>
Keyboard KeyEvent KeyListener keyPressed
28
keyReleased
keyTyped
Sources-events-listeners
Source Event Listener Methods
<state change> (argument:
correspondin
g event)
Button ActionEvent ActionListene ActionPerforme
<GUI button r d
clicked>
List ActionEvent ActionListene ActionPerforme
<item double r d
clicked>
ItemEvent ItemListener
ItemStateChan
<item ged
selected/deselecte
d>
29
import java.awt.*;
import java.awt.event.*;
Example 2
import javax.swing.*;
public class MouseEventsDemo extends JFrame
implements MouseListener {
JTextArea ta;
JScrollPane scrollPane;
public MouseEventsDemo(String title){
super(title);
ta = new JTextArea("start", 10, 20);
ta.setEditable(false);
scrollPane = new JScrollPane(ta);
// Register event listener to the event source
addMouseListener(this);
}
public void launchFrame() {// Displays GUI
add(scrollPane, BorderLayout.SOUTH);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 setVisible(true);
Example 2…
// Implement methods of event listener interface
public void mouseClicked(MouseEvent me) {
ta.append("\nMouse clicked at "+ me.getX()
+ ","
+ me.getY());
}
public void mouseEntered(MouseEvent me) {
ta.append("\nMouse entered component.");
}
public void mouseExited(MouseEvent me) {
ta.append("\nMouse exited component.");
}
public void mousePressed(MouseEvent me) {
ta.append("\nMouse pressed.");
}
public void mouseReleased(MouseEvent me) {
ta.append("\nMouse released.");
31
}
Example 2…
public static void main(String args[]) {// Main
method
MouseEventsDemo med =
new MouseEventsDemo("Mouse Events
Demo");
med.launchFrame();
}
}
Sample Output
32
Inner Class Listeners
A listener class is designed specifically to create a
listener
object for a GUI component (e.g., a button).
It will not be shared by other applications. So, it is
appropriate to define the listener class inside the
frame
class as an inner class.
An inner class, nested class, is a class defined within
the
scope of another class.
33
Inner Class Listeners …
public class Test { // OuterClass.java: inner class demo
... public class OuterClass {
} private int data;
34
Inner Class Listeners …
Example 1:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class SimpleEventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
37
Inner Class Example…
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
frame.setSize(200, 200);
frame.setVisible(true);
}// End of main() method
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or
interface
// Other methods if necessary
}
39
Anonymous Inner Classes ….
Example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
40
Anonymous Inner Classes…
jbtOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("It is OK");
}
});
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
} // end of class SimpleEventDemo
41
Multiple Listeners for a Single
Example
Source
setLayout(new FlowLayout());
add(jbtOK);
add(jbtCancel);
jbtOK.addActionListener(firstListener);
jbtCancel.addActionListener(firstListener);
jbtOK.addActionListener(secondListener);
42
jbtCancel.addActionListener(secondListener);
Multiple Listeners for a Single
Source
private class FirstListener implements ActionListener {
/** This method will be invoked when a button is
clicked */
public void actionPerformed(ActionEvent e) {
System.out.print("First listener: ");
if (e.getSource() == jbtOK) {
System.out.println("The OK button is clicked");
}
else if (e.getSource() == jbtCancel) {
System.out.println("The Cancel button is
clicked");
}
}
}
43
Multiple Listeners for a Single
Source
private class SecondListener implements
ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.print("Second listener: ");
if (e.getActionCommand().equals("OK")) {
System.out.println("The OK button is clicked");
}
else if (e.getActionCommand().equals("Cancel")) {
System.out.println("The Cancel button is
clicked");
}
}
}
44
Adapter classes
Many event-listener interfaces, such as
MouseListener and MouseMotionListener, contain
multiple methods.
It is not always desirable to declare every method in
an event-listener interface.
For instance, an application may need only the
mouseClicked handler from MouseListener or the
mouseDragged handler from MouseMotionListener.
For many of the listener interfaces that have
multiple methods, packages java.awt.event and
javax.swing.event provide event-listener adapter
classes.
An adapter class implements an interface and
provides a default implementation (with an empty
45
method body) of each method in the interface.
Adapter classes…
You can extend an adapter class to inherit
the default implementation of every method
and subsequently override only the
method(s) you need for event handling.
The convenience adapter is named XAdapter
for XListener.
Examlpe:
WindowAdapter is a convenience listener
adapter for WindowListener.
47
Exercise:
Develop a scientific
calculator in java
48