Lecture 13 Event Handling
Lecture 13 Event Handling
Lecture # 13
1
Course Books
◼ Text Book:
◼ Herbert Schildt, Java: The Complete Reference, McGraw-Hill
Education, Eleventh Edition
◼ Craig Larman, Applying UML & patterns, 2 edition
◼ Reference Books:
◼ Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
◼ Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition
2
Course Instructors
◼ Umm-e-Laila [email protected]
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536
3
Course Website
◼ http://sites.google.com/site/ulaila206
4
Event-Driven Programming
◼ Procedural programming is executed in
procedural order.
5
Events and Listeners
◼ 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 button clicks, and keystrokes, or by
the operating system, such as a timer.
◼ Events are responded to by event listeners
◼ The event causes a call to a method called
an event handler
6
The Delegation Model
7
Event Classes
ActionEvent ContainerEvent
TextEvent WindowEvent
ListSelectionEvent
8
Event Class Description
◼ ActionEvent Generated when a button is pressed, a list
item is double-clicked, or a menu item is selected.
◼ AdjustmentEvent Generated when a scroll bar is
manipulated.
◼ ComponentEvent Generated when a component is
hidden, moved, resized, or becomes visible.
◼ ContainerEvent Generated when a component is added
to or removed from a container.
◼ FocusEvent Generated when a component gains or
loses keyboard focus.
◼ ItemEvent Generated when a check box or list item is
clicked; also occurs when a choice selection is made or
a checkable menu item is selected or deselected.
9
◼ InputEvent Abstract super class for Mouse and Key
event classes.
◼ KeyEvent Generated when input is received from the
keyboard.
◼ MouseEvent Generated when the mouse is dragged,
moved, clicked, pressed, or released; also generated
when the mouse enters or exits a component.
◼ MouseWheelEvent Generated when the mouse wheel
is moved. (Added by Java 2, version 1.4)
◼ TextEvent Generated when the value of a text area or
text field is changed.
◼ WindowEvent Generated when a window is activated,
closed, deactivated, deiconified, iconified, opened, or
quit.
10
Event Representation
◼ Each event is represented by an object that
gives information about the event and
identifies the event source.
◼ In Java, every event is a subclass of
EventObject.
◼ Event sources are usually components, but
they can be other kind of objects too.
◼ An event source can have multiple event
listeners registered on it.
◼ Examples of event sources are e.g. buttons
and windows.
11
Sources of Events
◼ Button Generates action events when the button is pressed.
◼ Checkbox Generates item events when the check box is selected or
deselected.
◼ ComboBox(Choice) Generates item events when the choice is
changed.
◼ List Generates action events when an item is double-clicked;
generates item events when an item is selected or deselected.
◼ Menu Item Generates action events when a menu item is selected;
generates item events when a checkable menu item is selected or
deselected.
◼ Scrollbar Generates adjustment events when the scroll bar is
manipulated.
◼ Text components Generates text events when the user enters a
character.
◼ Window Generates window events when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
12
Selected User Actions
Source Event Type
User Action Object Generated
13
Abstract class EventObject
14
Event Listeners
15
Event Listeners
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
16
Event Listeners
17
How to Implement a Listener Interface
20
ActionListeners
◼ To listen for ActionEvents the class must
implement the interface ActionListener, that in
turn is an implementation of EventListener.
◼ ActionListener interface defines the
actionPerformed( ) method that is invoked when
an action event occurs. Its general form is
shown here:
21
Steps of ActionEvent handling
Approach 1:
1) import java.awt.event.*
2) Create class MyActionListner and implements
ActionListener
3) write method
public void actionPerformed(ActionEvent e)
in MyActionListner
4) call addActionListener(new MyActionListner())
for all Jbuttons in main Gui classs
22
Add call to event handler
import javax.swing.*; import java.awt.*;
class SimpleGUI extends Jframe {
Jbutton btn_one; Jlabel lb_result;
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn_one= new JButton(“Click me”);
lb_result=new JLabel(“Hello”);
setLayout(new FlowLayout();
btn_one.addActionListener(new MyActionListener());
add(lb_result); add(btn_one); setVisible(true);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”); }}
23
Event Handler Code
class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
lb_result.setText(“Hello Karachi”);
}
24
Add second button/event
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn_one= new JButton(“Click me”);
btn_two= new JButton(“Exit”);
lb_result=new JLabel(“Hello”);
setLayout(new FlowLayout();
btn_one.addActionListener(new MyActionListener());
add(lb_result); add(btn_one); add(btn_two);
setVisible(true);
}
25
How to distinguish event
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getActionCommand().equals(“Exit”){
System.exit(1); }
else if (ae.getActionCommand().equals(“Click me”){
lb_result.setText(“Hello Karachi”); }}
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == btn_two){
System.exit(1); Better way to find
} event source
else if (ae.getSource() == btn_one){
lb_result.setText(“Hello Karachi”); }}
26
Approach 2:
1) import java.awt.event.*
2) implements ActionListener
3) write method
public void
actionPerformed(ActionEvent e)
4) call addActionListener(this) for all
Jbuttons
27
Add call to event handler
import javax.swing.*; import java.awt.event.*;
class SimpleGUI extends Jframe implements ActionListener {
Jbutton btn_one; Jlabel lb_result;
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn_one= new JButton(“Click me”);
lb_result=new JLabel(“Hello”);
setLayout(new FlowLayout();
btn_one.addActionListener(this);
add(lb_result); add(btn_one); setVisible(true);
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}// end of main 28
Event Handler Code
public void actionPerformed(ActionEvent ae){
lb_result.setText(“Hello Karachi”);
}
29
Alternative Approaches to Listening
◼ Implement the listener with the main application class,
and have the one listener assigned to all components
generating the events
❑ Advantage: simplicity for beginner programmers
❑ Disadvantage: event-handler method may require if-statement or
switch with several branches when multiple components
generate the event
◼ Use inner classes to implement the listeners and create
a different instance as each component’s listener.
❑ Named inner class or anonymous inner class (This is the
approach used by netbeans self generated code)
❑ Advantage: no need to test within the listeners for determining
which component sent the event. Each component has its own
dedicated listener
❑ Disadvantage: harder to understand for novice programmers
30
Example with named
inner classes, one for
listening to each
button
31
Example with anonymous
inner classes, one for listening
to each button
32
The AdjustmentListener Interface
33
Example AdjustmentEvent
import java.awt.*; import java.awt.event.*;import javax.swing.*;
class ScrollbarExample extends JFrame{
ScrollbarExample(){
super("Scrollbar Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
//Constructs a new scroll bar with the specified orientation, initial value, page size, and
minimum and maximum values.
JScrollBar s=new JScrollBar(JScrollBar.HORIZONTAL, 0, 10, 0, 255);
s.setBounds(100,100, 255,10);
add(s);add(label);
this.getContentPane().setBackground(Color.yellow);
setSize(400,400);
34
setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}
public static void main(String args[]){
new ScrollbarExample();
}
}
35
Component Listener
◼ This interface deals with the component events. Following are the
event handling methods available in the ComponentListener
interface:
36
Example ComponentEvent
import java.awt.event.*; import javax.swing.*;
public class CompontlistnerCheck extends JFrame{
int i=0;
JCheckBox Chk_1;
JButton btn_1,btn_2;
CompontlistnerCheck (){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn_1=new JButton("Hide");
btn_2=new JButton("Move");
Chk_1 = new JCheckBox("Label visible", true);
Chk_1.addComponentListener(new ComponentListener() {
public void componentHidden(ComponentEvent e) {
System.out.println("componentHidden event from " + e.getComponent().getClass().getName());
}
public void componentMoved(ComponentEvent e) {
Component c = e.getComponent();
System.out.println("componentMoved event from " + c.getClass().getName()
+ "; new location: " + c.getLocation().x + ", " + c.getLocation().y);
}
37
public void componentResized(ComponentEvent e) {
Component c = e.getComponent();
System.out.println("componentResized event from " + c.getClass().getName() + "; new size: "
+ c.getSize().width + ", " + c.getSize().height);
}
38
add(btn_2,"East");
add(btn_1,"South");
add(Chk_1, "North");
setSize(300, 200);
setVisible(true);
}
public static void main(String[] a) {
CompontlistnerCheck obj=new CompontlistnerCheck();
}
39
Home Task
40