0% found this document useful (0 votes)
9 views

Lecture 13 Event Handling

oop

Uploaded by

aliza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lecture 13 Event Handling

oop

Uploaded by

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

Events Handling part 1

ActionEvent, AdjustmentEvent, ComponentEvent

Compiled By: Umm-e-Laila & Aneeta Siddiqui

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

◼ Aneeta Siddiqui [email protected]


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,

3
Course Website

◼ http://sites.google.com/site/ulaila206

4
Event-Driven Programming
◼ Procedural programming is executed in
procedural order.

◼ In event-driven programming, code is


executed upon activation of events.

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

Event-generating Objects send Events to Listener Objects


• Each event-generating object (usually a component) maintains a set
of listeners for each event that it generates.
• To be on the list, a listener object must register itself with the event-
generating object.
• Listeners have event-handling methods that respond to the event.

7
Event Classes

ActionEvent ContainerEvent

AdjustmentEvent FocusEvent MouseEvent

EventObject AWTEvent ComponentEvent InputEvent

ItemEvent PaintEvent KeyEvent

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

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 a new item JComboBox ItemEvent, ActionEvent
Select an item from a List JList ListSelectionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Any Component MouseEvent
Key released, pressed, etc. Any Component KeyEvent

13
Abstract class EventObject

◼ getSource returns the


object on which the
event occured.
◼ Each subclass adds
its own specialized
methods.

14
Event Listeners

◼ An event listener is an object that wants to be


notified when an event has occured on a
component.
◼ The common interface that all event listener
interfaces must extend is EventListener.

15
Event Listeners

Event Classes Listener Interfaces

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

◼ Use the implements keyword in the class


declaration
◼ Register the object as a listener for a
component’s event, using the component’s
addXListener method. (where X is the type of
event). (Typically done in constructor)
◼ Declare and fully define all methods for the
interface that you are implementing
❑ Requires:
◼ Complete method signature
◼ Method body

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:

◼ void actionPerformed(ActionEvent ae)

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

Inner class has


direct access to all
members (even
private) of the
outer class

31
Example with anonymous
inner classes, one for listening
to each button

32
The AdjustmentListener Interface

◼ This interface defines the adjustmentValueChanged()


method that is invoked when an adjustment event occurs.
Its general form is shown here:

◼ void adjustmentValueChanged (AdjustmentEvent ae)

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:

void componentResized(ComponentEvent ce)

void componentMoved(ComponentEvent ce)

void componentShown(ComponentEvent ce)

void componentHidden(ComponentEvent ce)

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

public void componentShown(ComponentEvent e) {


System.out.println("componentShown event from " + e.getComponent().getClass().getName());
}
});
btn_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(i%2==0)
Chk_1.hide();
else
Chk_1.setVisible(true);
i++;
} });
btn_2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
Chk_1.setLocation(i+200, i+200);
} });

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

◼ Create a Login form and apply event handling


◼ Previously TicTacToe board has been
designed by JButton
❑ Make the JButton text change to X when the user
clicks on it.
❑ Make the JButton text change to X and O
alternatively as the user clicks on the buttons.

40

You might also like