0% found this document useful (0 votes)
13 views48 pages

GUI - Event Handling

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views48 pages

GUI - Event Handling

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

1

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.

The event is generated by external user


actions such as mouse movements, mouse
clicks, and keystrokes, or by the operating
system, such as a timer.

Event is represented by an Event class


(e.g., ActionEvent, ComponentEvent ,
3 FocusEvent, KeyEvent, MouseEvent, etc).
Event Classes

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.

The component on which an event is fired or


generated is called the source object or
source component(Event source).

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 ….

An event object contains all necessary


information about the event that has
occurred
 Type of event that has occurred
 Source of the event using getSource()
instance method in the EventObject class.

7
User Action, Source Object, and
Event Type
Source Event Type
User Action Object Generated

Click a button JButton ActionEvent


Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select item(s) JList ListSelectionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent

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.

The latter object is called a Event


Listener ( or handler).

In java, there are different Event Listener


interface to create listener object to
10
handle every type of GUI events.
Listeners, Registrations, and
Handling Events
Two things are needed for an object to be a listener
for an event on the source object.
1)The listener object must be an instance of the
corresponding event- listener interface to ensure
that the listener has the correct method for
processing the event.

The listener interface is usually named XListener


for XEvent, with exception of MouseMotionListener.
Example:
The corresponding listener interface for
ActionEvent is ActionListener; each listener for
ActionEvent should implement the ActionListener
interface.
11
Events, Event Listener, and
Listener Methods
Event ClassListener Interface Listener Methods
(Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
12 keyReleased(KeyEvent)
keyTypeed(KeyEvent)
Listeners, Registrations, and
Handling Events…
2. The listener object must be registered by
the source object.
 To register listener object, we have a
registration methods which are
dependent on the event type.

Example: For ActionEvent, the method is


addActionListener.
 In general, the method is named
addXListener for XEvent.
13
Steps for Creating GUI Applications with
Event Handling
1. Create a GUI class
 Describes and displays the appearance of your GUI
application
2. Create Event Listener class (a class implementing the
appropriate listener interface)
 Override all methods of the appropriate listener
interface
 Describe in each method how you would like the event
to be handled
 May give empty implementations for methods you don't
need
3. Register the listener object with the event source
 The object is an instantiation of the listener class in step
2
14  Use the add<Type>Listener method of the event source
Listeners, Registrations, and
Handling Events…
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();

JButton jbtOK = new JButton("OK");


frame.setLayout(new FlowLayout());
frame.add(jbtOK);

OKListener listener = new OKListener();


jbtOK.addActionListener(listener);

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

class OKListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
System.out.println("OK button is Clicked");
}
} // end of class OKListener
16
Listeners, Registrations, and
Handling Events…

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);

• When you click the button, the Jbutton object


fires an ActionEvent and passes it to invoke the
listener’s actionPerformed method to handle the
event.
19
java.awt.event.ActionEve
nt

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;

public class A { /** A method in the outer class */


... public void m() {
} // Do something
}
(a)
// An inner class
class InnerClass {
public class Test { /** A method in the inner class */
... public void mi() {
// Directly reference data and method
// Inner class // defined in its outer class
public class A { data++;
... m();
} }
} }
}
(b)
(c)

34
Inner Class Listeners …

Inner class: A class is a member of


another class.
Advantages: In some applications, you
can use an inner class to make programs
simple.
An inner class can reference the data and
methods defined in the outer class in
which it nests, so you do not need to pass
the reference of the outer class to the
constructor
35 of the inner class.
Inner Class….
Inner classes can make programs simple and
concise.
An inner class supports the work of its containing
outer class and is compiled into a class named
OuterClassName$InnerClassName.class.
For example, the inner class InnerClass in
OuterClass is compiled into
OuterClass$InnerClass.class.
An inner class can be declared public, protected,
or private subject to the same visibility rules
applied to a member of the class.
An inner class can be declared static. A static
inner class can be accessed using the outer class
name. A static inner class cannot access
nonstatic members of the outer class
36
Inner Class Example

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();

JButton jbtOK = new JButton("OK");


frame.setLayout(new FlowLayout());
frame.add(jbtOK);

OKListener listener = new OKListener();


jbtOK.addActionListener(listener);

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

class OKListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
System.out.println("It is OK");
}
} // end of class OKListener

}//end of class SimpleEventDemo


38
Anonymous Inner Classes
Inner class listeners can be shortened using anonymous
inner classes.
An anonymous inner class is an inner class without a
name.
 It combines declaring an inner class and creating an
instance of the class in one step.
 An anonymous inner class is declared as follows:

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.*;

public class SimpleEventDemo {


public static void main(String[] args) {

JFrame frame = new JFrame();

JButton jbtOK = new JButton("OK");


frame.setLayout(new FlowLayout());
frame.add(jbtOK);

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);

// Register the first listeners


ActionListener firstListener = new FirstListener();

jbtOK.addActionListener(firstListener);
jbtCancel.addActionListener(firstListener);

// Register the second listener for buttons


ActionListener secondListener = new
SecondListener();

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.

See TestWindowEvent.java and


46
AdapterDemo.java
Adapter classes…

47
Exercise:
Develop a scientific
calculator in java

48

You might also like