Unit-3 Event-Handling
Unit-3 Event-Handling
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
• Changing the state of an object is known as an
event.
• For example: clicking on a button, Entering a
character in Textbox, moving the mouse,
selecting an item from list, scrolling the page,
etc.
• The java.awt.event package provides many
event classes and Listener interfaces for event
handling.
2
Delegation Event Model
• The modern approach to handling events is
based on the delegation event model.
• The delegation event model provides a standard
mechanism for a source to generate an event
and send it to a set of listeners.
• The listener simply waits until it receives an
event.
• Once received, the listener processes the event
and then return.
3
• In the delegation event model, listener must
register with a source in order to receive an
event notification.
• Notification are sent only to listeners that
want to receive them.
• There are mainly three parts in delegation
event model.
– Events.
– Event sources.
– Event Listeners.
4
Components of Event Handling
Event handling has three main components:
events, event sources, event listeners.
• Events
An event is a change of state of an object.
– Events may also occur that are not directly caused
by interactions with a user interface. For example,
an event may be generated when a timer expires,
a counter exceeds a value, software or hardware
failure occurs, or an operation is completed.
5
Event Sources
• A source is an object that generates an event.
This occurs when the internal state of that object
changes in some way.
• Sources may generate more than one type of
event.
• A source must register listeners in order for the
listeners to receive notifications about a specific
type of event.
• Each type of event has its own registration
method.
6
Event Listeners
• A listener is an object that is notified when an
event occurs.
• It has two major requirements. First, it must
have been registered with one or more sources
to receive notifications about specific types of
events.
• Second, it must implement methods to receive
and process these notifications.
• The method that receive and process events are
defined in a set of interfaces found in
java.awt.event.
7
• Here is the general form to register listeners:
– public void addTypeListener(TypeListener el)
– For example: b.addActionListener(this);
• Here, type is the name of the event, and el is a
reference to the event listener.
• For example, the method that registers a
keyboard event listener is called
addKeyListener().
• The method that registers a mouse motion
listener is called addMouseMotionListener().
• When an event occurs, all registered listeners are
notified and receive a copy of the event object.
8
• The general form of unregister listener
method is this:
9
Advanced Java Programming
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Event
• Event Delegation Model
12
Important Event Classes
and Interface
13
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is selected, ActionListener
list-item is double clicked
15
Registration Methods
For registering the component with the Listener, many classes provide
the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){} 16
KeyEvent class
• An event which indicates that a keystroke occurred in a component.
17
• There are many other integer constants that are
defined by KeyEvent. For example
– VK_0 to VK_9
– VK_A to VK_Z define the ASCII equivalents of the
numbers and letters.
• Key events are fired by the component with the keyboard focus
when the user presses or releases keyboard keys.
20
• The first kind of event is called a key-typed event.
• To know when the user presses the F1 key, or whether the user
pressed the '3' key on the number pad, you handle key-pressed events.
21
Methods of KeyListener Interface
Method Purpose
keyTyped(KeyEvent) Called just after the user types a
Unicode character into the listened-
to component.
keyPressed(KeyEvent) Called just after the user presses a
key while the listened-to
component has the focus.
keyReleased(KeyEvent) Called just after the user releases a
key while the listened-to
component has the focus.
22
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class Keydemo2 extends Applet implements KeyListener
{
String str="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
str="Key Pressed";
}
public void keyReleased(KeyEvent ke)
{
str="Key Released";
repaint();
}
public void keyTyped(KeyEvent ke)
{
showStatus("Key Typed");
}
23
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
24
25
Advanced Java Programming
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Sources generating Event.
• Important Event classes & Interfaces.
• Key Event Class.
• Key Listener Interface.
• Key Event Methods.
MouseEvent class
This event indicates a mouse action occurred in a
component. This low-level event is generated by a
component object for Mouse Events and Mouse
motion events.
28
Methods of MouseListener Interface
Method Purpose
mouseClicked(MouseEvent) Called just after the user clicks the
listened-to component.
mouseEntered(MouseEvent) Called just after the cursor enters
the bounds of the listened-to
component.
mouseExited(MouseEvent) Called just after the cursor exits the
bounds of the listened-to
component.
mousePressed(MouseEvent) Called just after the user presses a
mouse button while the cursor is
over the listened-to component.
mouseReleased(MouseEvent) Called just after the user releases a
mouse button after a mouse press
over the listened-to component.
29
Method Purpose
30
MouseListener Interface
• Mouse events notify when the user uses the mouse (or similar input
device) to interact with a component.
31
MouseMotionListener Interface
• Mouse-motion events notify when the user uses the mouse (or a
similar input device) to move the onscreen cursor.
32
Methods of MouseMotionListener Interface
Method Purpose
33
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class mousedemo extends Applet implements MouseListener
{
TextArea t;
int mx=0,my=0;
public void init()
{
t=new TextArea();
add(t);
addMouseListener(this);
}
public void mouseEntered(MouseEvent me)
{
t.setText("Mouse Entered");
}
public void mouseClicked(MouseEvent me)
{
t.setText("Mouse Clicked"); 34
public void mousePressed(MouseEvent me)
{
mx=me.getX();
my=me.getY();
t.setText("Mouse Pressed At:"+mx+","+my);
}
public void mouseReleased(MouseEvent me)
{
t.setText("Mouse Released");
}
public void mouseExited(MouseEvent me)
{
t.setText("Mouse Exited");
}
}
35
36
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class mousemotiondemo1 extends Applet implements
MouseMotionListener
{
TextArea t;
int mx=0,my=0;
public void init()
{
t=new TextArea();
add(t);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent me)
{
t.setText("Mouse Moved");
}
37
public void mouseDragged(MouseEvent me)
{
t.setText("Mouse Dragged");
}
}
38
39
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class mousemotiondemo extends Applet implements
MouseListener,MouseMotionListener
{
TextArea t;
int mx=0,my=0;
public void init()
{
t=new TextArea();
add(t);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent me)
{
t.setText("Mouse Entered");
}
40
public void mouseClicked(MouseEvent me)
{
t.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent me)
{
mx=me.getX();
my=me.getY();
t.setText("Mouse Pressed At:"+mx+","+my);
}
public void mouseReleased(MouseEvent me)
{
t.setText("Mouse Released");
}
public void mouseExited(MouseEvent me)
{
t.setText("Mouse Exited");
}
public void mouseMoved(MouseEvent me)
{
t.setText("Mouse Moved"); 41
public void mouseDragged(MouseEvent me)
{
t.setText("Mouse Dragged");
}
}
42
43
Advanced Java Programming
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Mouse Event Class
• Mouse Listener interface
• Mouse Motion Listener interface
ActionEvent Class
• An ActionEvent is generated when a button is
pressed, a list item is double-clicked, or a
menu item is selected.
46
ActionListener Interface
47
Methods
• public String getActionCommand()
– Returns the command string associated with this
action.
48
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
if(action.equals("Ok"))
str = "Ok Button Pressed";
else if(action.equals("Cancel"))
str = "Cancel Button Pressed";
repaint();
}
}
50
51
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class multiply extends Applet implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public void init()
{
setLayout(new GridLayout(4,2));
l1=new Label("Enter first No.");
l2=new Label("Enter second No.");
l3=new Label("Multiplication");
t1=new TextField();
t2=new TextField();
t3=new TextField();
b1=new Button("Multiply");
add(l1);
add(t1);
add(l2);
add(t2); 52
add(l3);
add(t3);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
int n3=n1*n2;
t3.setText(Integer.toString(n3));
}
}
}
• void itemStateChanged(ItemEvent e)
• Invoked when an item has been selected or
deselected by the user.
• The code written for this method performs the
operations that need to occur when an item is
selected (or deselected).
59
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Checkbox java,vb,c;
60
public void init()
{
java = new Checkbox("Java");
vb = new Checkbox("Visual Basic");
c = new Checkbox("C");
add(java);
add(vb);
add(c);
java.addItemListener(this);
vb.addItemListener(this);
c.addItemListener(this);
}
public void paint(Graphics g)
{
g.drawString("Java: " + java.getState(),10,80);
g.drawString("VB: " + vb.getState(), 10, 100);
g.drawString("C: " + c.getState(), 10, 120);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
} 61
}
62
Advanced Java Programming
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Focus Event Class
• Focus Listener interface
ComponentEvent class
• A low-level event which indicates that a component moved,
changed size, or changed visibility.
• This class has following constants.
• public static final int COMPONENT_MOVED
– This event indicates that the component's position changed.
• public static final int COMPONENT_RESIZED
– This event indicates that the component's size changed.
• public static final int COMPONENT_SHOWN
– This event indicates that the component was made visible.
• public static final int COMPONENT_HIDDEN
– This event indicates that the component was become
invisible.
65
ComponentLIstener interface
• The listener interface for receiving component
events.
• void componentResized(ComponentEvent e)
– Invoked when the component's size changes.
• void componentMoved(ComponentEvent e)
– Invoked when the component's position changes
• void componentShown(ComponentEvent e)
– Invoked when the component has been made visible.
• void componentHidden(ComponentEvent e)
– Invoked when the component has been made
invisible.
66
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class ComponentEventExample1 extends JFrame implements
ComponentListener
{
JTextArea t1;
JCheckBox c1,c2;
public ComponentEventExample1()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t1 = new JTextArea();
c1 = new JCheckBox("Checkbox 1");
c2 = new JCheckBox("Checkbox 2");
add(t1, BorderLayout.CENTER);
add(c1, BorderLayout.NORTH);
add(c2, BorderLayout.SOUTH);
setVisible(true);
addComponentListener(this);
} 67
public void componentShown(ComponentEvent evt)
{
System.out.println("componentShown");
}
public void componentHidden(ComponentEvent evt)
{
System.out.println("componentHidden");
}
public void componentMoved(ComponentEvent evt)
{
System.out.println("componentMoved");
}
public void componentResized(ComponentEvent evt)
{
System.out.println("componentResized");
}
public static void main(String[] args)
{
new ComponentEventExample1();
}
} 68
69
ContainerEvent class
• A low-level event which indicates that a container's
contents changed because a component was added or
removed
• This class has following constants.
• public static final int COMPONENT_ADDED
– This event indicates that a component was added
to the container.
• public static final int COMPONENT_REMOVED
– This event indicates that a component was
removed from the container.
70
• public Container getContainer()
– Returns the originator of the event.
– Returns the Container object that originated the
event, or null if the object is not a Container.
71
ContainerListener interface
– The listener interface for receiving container events.
• void componentAdded(ContainerEvent e)
– Invoked when a component has been added to the
container.
72
Adjustment Event class
• AdjustmentEvent class and
AdjustmentListener interface are used for
handling event for scrollbar.
73
AdjustmentListener interface
• This event class and Listener interface are
associalted with Scrollbar component
adjustmentValueChanged() contains the logic
to perform any operation if scrollbar position
is changed.
74
Methods of AdjustmentEvent Class
a) Adjustable getAdjustable()
• Returns the Adjustable object where this event originated.
b) int getAdjustmentType()
• Returns the type of adjustment which caused the value changed event.
c) int getValue()
• Returns the current value in the adjustment event.
d) boolean getValueIsAdjusting()
• Returns true if this is one of multiple adjustment events.
e) String paramString()
• Returns a string representing the state of this Event. 75
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Exp8_3 extends Applet implements AdjustmentListener
{
Scrollbar sb1,sb2,sb3;
public void init()
{
sb1=new Scrollbar(Scrollbar.HORIZONTAL);
sb2=new Scrollbar(Scrollbar.HORIZONTAL);
sb3=new Scrollbar(Scrollbar.HORIZONTAL);
add(sb1);
add(sb2);
add(sb3);
76
sb1.addAdjustmentListener(this);
sb2.addAdjustmentListener(this);
sb3.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
int red=sb1.getValue();
int green=sb2.getValue();
int blue=sb3.getValue();
setBackground(new Color(red,green,blue));
}
}
/*<Applet code=Exp8_3.class height=500 width=400></Applet>*/
77
78
Advanced Java Programming
Unit-3
Event Handling
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Recap
• Item Event Class
• Item Listener interface
TextEvent class
• A semantic event which indicates that an object's
text changed.
• This high-level event is generated by an object
(such as a TextComponent TextField and
TextArea) when its text changes.
81
TextListener interface
• void textValueChanged(TextEvent e)
• Invoked when the value of the text has
changed.
• The code written for this method performs the
operations that need to occur when text
changes.
82
Method of TextEvent class
public String paramString() Returns the String describing the
TextEvent.
83
import java.awt.*;
import java.awt.event.*;
public class TextEventEx1 extends Frame implements TextListener
{
Label label1, label2;
TextField field1;
String str;
TextEventEx1()
{
label1= new Label("Type in the textfield, to see the textevents it generates -",
Label.CENTER);
label2= new Label();
field1 = new TextField(25);
setLayout(new FlowLayout());
add(label1);
add(field1);
add(label2);
field1.addTextListener(this);
setSize(340,200);
setVisible(true); 84
}
public void textValueChanged(TextEvent te)
{
label2.setText(te.paramString());
setVisible(true);
}
public static void main(String... ar)
{
new TextEventEx1();
}
}
85
86
FocusEvent class
87
FocusListener interface
• void focusGained(FocusEvent e)
– Invoked when a component gains the keyboard
focus.
• void focusLost(FocusEvent e)
– Invoked when a component loses the keyboard
focus.
88
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public FocusListenerExample()
{
b1=new Button ("First");
b2=new Button ("Second");
add(b1,BorderLayout.SOUTH);
add(b2,BorderLayout.NORTH);
b1.addFocusListener(this);
b2.addFocusListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
} 89
public void focusGained(FocusEvent fe)
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"gained");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"gained");
if(fe.isTemporary())
System.out.println("Temporary Focus");
}
public void focusLost(FocusEvent fe)
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"lost");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"lost");
}
public static void main(String a[])
{
new FocusListenerExample();
}
} 90
91
WindowEvent and WindowListener
92
Method of WindowEvent class
public void windowOpened(WindowEvent e) This method is called when a window is opened for
the first time.
This method is called when a window shows up on
public void windowActivated(WindowEvent e) screen.
public void windowDeactivated(WindowEvent e) This method is called is no longer the window in use
or active.
public void windowClosed(WindowEvent e) This method is called when a window has been
closed.
93
94
95
96
97