100% found this document useful (1 vote)
69 views

GUI - Event Handling (2) - Lecture

The document discusses event handling in Java GUI programming. It explains that events are generated by user interactions or the operating system and are represented by event objects. Components that generate events are called event sources. Listeners implement listener interfaces and are registered with sources to handle specific event types. The key aspects covered are the roles of events, sources, listeners, registering listeners, and listener method signatures.

Uploaded by

Biruk Markos
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
69 views

GUI - Event Handling (2) - Lecture

The document discusses event handling in Java GUI programming. It explains that events are generated by user interactions or the operating system and are represented by event objects. Components that generate events are called event sources. Listeners implement listener interfaces and are registered with sources to handle specific event types. The key aspects covered are the roles of events, sources, listeners, registering listeners, and listener method signatures.

Uploaded by

Biruk Markos
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Advanced Programming

Chapter two cont..: Event Handling


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.
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 important
players : Event, Event Source, and Event Listener (or
2 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 , FocusEvent,
KeyEvent, MouseEvent, etc).
3
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 is generated. )

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

5
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

6
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 handle every type of GUI
events.
7
Listeners, Registrations, and Handling Events
Two things 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,
Example:
The corresponding listener interface for ActionEvent is
ActionListener; each listener for ActionEvent should
implement the ActionListener interface.
8
Events, Event Listener, and Listener Methods

Event Class Listener 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)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
9
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.

10
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
Use the add<Type>Listener method of the event source
11
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);
12
Listeners, Registrations, and Handling
Events…
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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

13
Listeners, Registrations, and Handling
Events…
Example 2
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.*;
public class MyEvent extends JFrame {
JButton b1;
public MyEvent(){
super("Window Title: Event Handling");
b1 = new JButton("Click Me");
add(b1, BorderLayout.NORTH);

ButtonListener listen = new ButtonListener();


b1.addActionListener(listen);

setSize(200,200);
14
setVisible(true);
}
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, ...!");
}
}

15
Event-listeners

ActionListener Method
Contains exactly one method

16
Event-listeners…
MouseListener Methods

17
Event-listeners…
MouseMotionListener Methods

18
Event-listeners…
WindowListener Methods

19
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 has been
20
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.

21
Sources-events-listeners
Source Event object Listener Methods
<state change> (argument:
corresponding event)
Mouse MouseEvent MouseListener mouseClicked
<mouse clicked, pressed, mousePressed
dragged, moved/ mouseReleased etc
entered, exited a
component etc> MouseMotionListen mouseDragged
er mouseMoved

mouseWheelMove
MouseWheelEvent MouseWheelListene d
<page-up and down> r
Keyboard KeyEvent KeyListener keyPressed
keyReleased
keyTyped

22
Sources-events-listeners
Source Event Listener Methods
<state change> (argument:
corresponding
event)
Button ActionEvent ActionListener ActionPerformed
<GUI button clicked>

List ActionEvent ActionListener ActionPerformed


<item double clicked>
ItemEvent ItemListener
ItemStateChanged
<item
selected/deselected>

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

24
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 of the inner class.

25
Inner Class….
Inner classes can make programs simple and
concise.
An inner class can be declared public, protected, or
private subject to the same visibility rules applied
to a member of the class.

26
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);
27
Inner Class Example…

frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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

28
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
}

29
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);
30
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
31
Multiple Listeners for a Single Source
Example
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);
jbtCancel.addActionListener(secondListener);
32
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");
}
}
}

33
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");
}
}
}

34
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 method body) of
35 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 AdapterDemo.java


36
Adapter classes…

37
Exercise:
Develop a scientific calculator in java

38

You might also like