SlideShare a Scribd company logo
1 of 91
Download to read offline
Advanced Java Programming
by
Amol S. Gaikwad
Lecturer,
Government Polytechnic Gadchiroli
Maharashtra
Advanced Java Programming
Unit-III
Event Handling
Welcome!
Are you excited for a fun
learning session?
Unit Outcomes
Use delegation event model to develop event driven program for the given
problem
Use relevant AWT/Swing component to handle the given event
Use adapter classes in java program to solve the given problem
Use inner classes in java program to solve the given problem
Introduction to Events
Events are an important part of applet programming
Applets are controlled by events
Events are generated by variety of sources such as :
user keyboard mouse
Introduction to Events
Events are generated by variety of sources such as :
Various controls
buttons
checkbox
choice
list
textfield
textarea
etc.
For handling events java.awt.event package is used
Delegation Event Model
Delegation event model is a modern approach for handling events
In this model there is a source, which generates event and there is listener which
receives the event from the source
The listener waits for the event and process the event when it is recieved
This seperates the logic of user interface and application logic that processes the
event
In this model, the listener must register with source for receiving event
notification
Due to this only that listener receives event which want to receive and process it
What is Event ?
In delegation event model, an event is an object which
contains all the information about change of state of
source of event
Events are generated when user interacts with
graphical user interface (GUI )
It is also generated when user presses button, or
key on keyboard or selects option from list, choice,
checkbox etc.
There are also other indirect sources of events,
which are not caused by interaction of user with
graphical user interface (GUI)
Fig: GUI
Other indirect sources of events are as follow :
What is Event ?
timer: when
time expires
counter : when count
reaches a value
software : when
software failure occurs
hardware : when hardware failure occurs
In java, source of an event is an object which generates an event
What is Event ?
When state of source of an object changes it generates an event
Source can generate more than one type of event
A source should register the listeners, so that the listener can get notification of
event
The general form of registration for an event is written as :
public void addTypeListener(TypeListener el)
Where, Type = name of event
el = reference to event listener
For example, if we want to register listener for keyboard event then we can write
as - addKeyListener( ),
Similarly, for registering listener for mouse motion, we can write as -
addMouseMotionListener( )
What is Event ?
When all registered listeners are notified and receives copy of event object it is
called as multicasting
Some sources of events allows only one listener to register, the general form of
such methods is as below :
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
When only one listener is notified of event it is called as unicasting
What is Event ?
Source of an event is also provides a method for removing or unregistering listener,
the syntax of the method is given as below:
public void removeTypeListener(TypeListener el)
For example, the method for removing or unregistering keyboard listener is
written as :
removeKeyListener( );
Component class provides methods (functions) to add and remove keyboard and
mouse event listeners
Event Listeners
Listeners are objects that receives notification when an event occurs
A listener must be register with one or more source to receive notification of an
event
It should have methods (functions) to receive and process the event notification
Methods that receive and process events are defined (found) in a group of
interfaces in java.awt.event package
Event Classes
In java there are classes that represents events, such classes are called as Event
classes
EventObject class is a root class of java's event class heirarchy
EventObject class is present in java.util package
It is super class (top most class) for all types of events
Constructor EventObject(Object src), where src = object that generates the event
Methods (functions) of EvenObject class :
getSource( ) - returns source of event
toString( ) - returns string description of event
Event Classes
The AWTEvent class is superclass (top most class) of all AWT-based events used by
delegation event model
The AWTEvent class is present in java.awt package, it is subclass (child class) of
EventObject class
int getID( ) - tells type of event
java.awt.event package describes several types of events
Event Classes
ActionEvent
AdjusmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
TextEvent
WindowEvent
Event Classes
KeyEvent
MouseEvent
MouseWheelEvent
ActionEvent Class
ActionEvent is created when - button is pressed, list item is double clicked or menu
item is selected
ActionEvent has four integer constants :
ALT_MASK = whether ALT key was pressed
CTRL_MASK = whether CTRL key was pressed
META_MASK = whether META key was pressed
SHIFT_MASK = whether SHIFT key was pressed
ActionEvent class has three constructors :
ActionEvent(Object src,int type,String cmd)
, ActionEvent( Object src,int type,String cmd,int modifiers)
ActionEvent( Object src,int type,String cmd, long when, int modifiers)
ActionEvent Class
Where :
src = reference to object that generated the event
type = what type of event is
cmd = command string of event
modifier keys = ALT,CTRL,META or SHIFT keys were pressed or not
when = when the event has occured
String getActionCommand( ) - returns command name of event object
int getModifiers( ) - returns which modifier key was pressed when event occured
int getWhen( ) - returns the time when event occurs (timestamp)
AdjustmentEvent Class
AdjustmentEvent is created by scroll bar
Five types of AdjustmentEvent are as follows :
BLOCK_DECREMENT = when user clicks inside scroll bar to decrease its value
BLOCK_INCREMENT = when user clicks inside scroll bar to increase its value
TRACK = when the slider is dragged
UNIT_DECREMENT = when button at the end of scroll bar is clicked to decrease
it's value
UNIT_INCREMENT = when button at the end of scroll bar is clicked to increase it's
value
AdjustmentEvent Class
ADJUSTMENT_VALUE_CHANGED - tells whether change has occured or not
AdjustmentEvent class has one constructor :
AdjustmentEvent(Adjustable src, int id, int type, int data)
Where src = reference to the object that generated the event
id = ADJUSTMENT_VALUE_CHANGED
type = type of event
data = data related to the event
Adjustable getAdjustable( ) - returns the object that generates the event
int getAdjustmentType( ) - returns the type of adjusment events from five types of
events
int getValue( ) - returns how much scroll bar is changed
ComponentEvent Class
ComponentEvent is created when the size, position,or visibility of component is
changed
Four types of ComponentEvent indentified by integer constants are as follows :
COMPONENT_HIDDEN = the component was hidden
COMPONENT_MOVED = the component was moved
COMPONENT_RESIZED = the component was resized
COMPONENT_SHOWN= the component becomes visible
ComponentEvent Class
ComponentEvent class constructor :
ComponentEvent(Component src, int type)
ComponentEvent class is superclass (parent class) of ContainerEvent class,
FocusEvent class, KeyEvent class, MouseEvent class ans WindowEvent class
Component getComponent( ) - returns the component that generated the event
ContainerEvent Class
ContainerEvent is created when a component is added to or removed from a
container
Two types of ContainerEvent identified by integer constant are as follow :
COMPONENT_ADDED = when component is added to the container
COMPONENT_REMOVED = when component is removed from the container
ContainerEvent class is subclass(child class) of ComponentEvent class
ContainerEvent(Component src, int type, Component comp)
src = reference to container that generated the event
comp = component that is added or removed from the container
type = type of event
ContainerEvent Class
Container getContainer( ) - returns reference to the container that generated this
event
Component getChild( ) - returns reference to the component that was added to or
removed from the container
FocusEvent Class
FocusEvent is created when a component gets or loses input focus
Three constructors of FocusEvent class are as follow :
FocusEvent class is subclass(child class) of ComponentEvent class
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
Where src = reference to component that generated the event
type = type of event
FocusEvent Class
temoraryFlag has value true or false
temoraryFlag has value true if the focus event is temporary otherwise false
Suppose our focus is in a text field and move the mouse to adjust scroll bar then
we called the focus is temporary lost
the other component is a opposite component when focus changes
When the event type is FOCUS_GAINED, the other component is that component
which lost focus
Similarly, when the event type is FOCUS_LOST, the other component is that
component which gains focus
FocusEvent Class
Two types of Focus Event identified by integer constant are as follow :
FOCUS_GAINED = when the component gains the input focus
FOCUS_LOST = when the component loses the input focus
Component getOppositeComponent( ) - this method returns the opposite
component that got or lost the input focus
boolean isTemporary( ) - this method returns whether the focus change is
temporary or not, true means focus change is temporary
ItemEvent Class
An ItemEvent is created when - checkbox or list item is clicked, when checkable
menu item is selected or deselected
DESELECTED - when an item is deselected by the user
Two types of ItemEvent identified by integer constant are as follow :
SELECTED - when an item is selected by the user
ITEM_STATE_CHANGED - this constant tells whether the state is changed or not
ItemEvent( ItemSelectable src, int type, Object entry, int state)
where src = the component that generated this event
type = type of event
ItemEvent Class
Where entry = item of checkbox or list or checkable menu item that generated the
event
state = the current state of the item
Object getItem( ) - this method returns reference to the item that generated the
event
ItemSelectable getItemSelectable( ) - this method returns reference to the
itemSelectable object that generated the event
List and Choice implements (inherits) ItemSelectable interface
int getStateChange( ) - this method returns the changed state for an event
KeyEvent Class
KeyEvent is created when we give input from keyboard
KeyEvent class is a subclass (child class) of InputEvent class
Three types of KeyEvent identified by integer constant are as follow :
KEY_PRESSED - when a key is pressed
KEY_RELEASED - when a key is released
KEY_TYPED - when a character is generated by typing a key
There are some keys which when pressed do not generate character, like SHIFT
key
KeyEvent Class
KeyEvent class has various integer constants which are as follow :
VK_0 to VK_9 = ASCII value of numbers
VK_A to VK_Z = ASCII value of letters
Other integer constants are as follow :
VK_ENTER
VK_DOWN
VK_PAGE_UP
VK_ESCAPE
VK_LEFT
VK_SHIFT
VK_CANCEL
VK_RIGHT
VK_ALT
VK_UP
VK_PAGE_DOWN
VK_CONTROL
VK constants means virtual key codes
KeyEvent Class
Constructors of KeyEvent class are as follow :
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Where src = reference to component that generated the event
type = type of event
modifiers = which modifier key pressed (control,shift,alt) when key event occured
code = VK_UP or VK_A code is passed here
ch = character equivalent is passed here, if not present then CHAR_UNDEFINED is
passed here
when= system time when KeyEvent occured
char getKeyChar( ) - returns the character that was entered, if valid character is
available then it returns CHAR_UNDEFINED,
int getKeyCode( ) - returns key code,when KEY_TYPED event occurs it returns
VK_UNDEFINED
KeyEvent Class
MouseEvent Class
MouseEvent is created when we interact with mouse
Eight types of MouseEvent identified by integer constant are as follow :
MOUSE_CLICKED = when the mouse is clicked by the user
MOUSE_DRAGGED = when the mouse is dragged by the user
MOUSE_ENTERED = when mouse enters a component
MOUSE_EXITED = when mouse exits a component
MOUSE_MOVED = when the mouse is moved
MOUSE_PRESSED = when the mouse is pressed
MOUSE_RELEASED = when the mouse is released
MOUSE_WHEEL = when the mouse wheel is moved
MouseEvent Class
MouseEvent class is subclass (child class) of InputEvent class
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks, boolean triggersPopup)
Where src = reference to component that generated the event
type = type of event
when= system time when MouseEvent occured
modifiers = which modifier key pressed (control,shift,alt) when mouse event
occured
x, y = x and y coordinates of mouse position
triggersPopup = whether pop up menu appears in this mouse event
MouseEvent Class
int getX( ) - returns x coordinate of mouse position when event occured
int getY( ) - returns y coordinate of mouse position when event occured
Point getPoint( ) - returns Point object containing x and y coordinates of mouse
void translatePoint(int x, int y) - changes the location of mouse event by adding x
and y to the old coordinates of mouse event
int getClickCount( ) - number of times mouse is clicked in this event
boolean inPopupTrigger( ) - whether this mouse event causes popup menu to
appear
int getButton( ) - returns a value that tells which button caused the event, the
value can be constants like - NOBUTTON, BUTTON1, BUTTON2, BUTTON3
MouseWheelEvent Class
MouseWheelEvent is created when we interact with mouse wheel
MouseWheelEvent class is subclass (child class) of MouseEvent class
Two types of MouseWheelEvent identified by integer constant are as follow :
WHEEL_BLOCK_SCROLL= when page-up or page-down scroll event occurs
Mouse wheels are used for scrolling
WHEEL_UNIT_SCROLL= when line-up or line-down scroll event occurs
MouseWheelEvent( Component src, int type, long when, int modifiers, intx, int y,
int clicks, boolean triggrtPopup, int scrollHow, int amount, int count)
MouseWheelEvent Class
Where src = reference to component that generated the event
type = type of event
when= system time when MouseEvent occured
modifiers = which modifier key pressed (control,shift,alt) when mouse event
occured
x, y = x and y coordinates of mouse position
triggersPopup = whether pop up menu appears in this mouse event
scrollHow = constants WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL
amounts = number of units to scroll
count = number of rotations the wheel of mouse has done
MouseWheelEvent Class
int getWheelRotation( ) - returns the number of rotations the mouse wheel has
done
int getScrollTypes( ) - returns typeof scroll whether WHEEL_UNIT_SCROLL type or
WHEEL_BLOCK_SCROLL type
int getScrollAmount( ) - if scoll type is WHEEL_UNIT_SCROLL, then this function
returns the number of units to scroll
TextEvent Class
TextEvents are created when user or program enters some characters in text
fields or text areas
TextEvent class has a one integer constant TEXT_VALUE_CHANGED
TextEvent class has one constructor which is as follow :
TextEvent( Object src, int type)
Where src = reference to object that generated the event
type = type of event
WindowEvent Class
WindowEvents are created when we interact with windows
WINDOW_ACTIVATED = when window is activated
Ten types of WindowEvent identified by integer constant are as follow :
WINDOW_CLOSED = when window is closed
WINDOW_CLOSING = when user requests to close the window
WINDOW_DEACTIVATED = when the window is deactivated
WINDOW_DEICONIFIED = when the window is deiconified
WINDOW_LOS_FOCUS = when the window loses the input focus
WINDOW_LOS_OPENED = when the window is opened
WINDOW_STATE_CHANGED = when the state of window is changed
WindowEvent Class
WindowEvents class is subclass (child class) of ComponentEvent class
WindowEvent( Window src, int type)
The constructors of WindowEvent class are as follow :
WindowEvent( Window src, int type, Window other)
WindowEvent( Window src, int type, int fromstate, int tostate)
WindowEvent( Window src, int type, Window other, int fromstate, int tostate
Where src = reference to object that generated the event
type = type of event
other = opposite window when focus event occurs
WindowEvent Class
fromstate = previous state of window
tostate = new state of window, when window changes its state
Window getWindow( ) - returns Window object that generated the event
Window getOppositeWindow( ) - returns opposite window when focus event occurs
int getOldState( ) - returns the previous state (old state) of window
int getNewState( ) - returns the new state of window
Event Listener Interfaces
Delegation
Event Model
Listener
Interfaces
sources and listeners are two
parts of delegation event model of
event handling
Listeners are created by
implementing (inheriting) one or
more interfaces
Listener interfaces are present in
java.awt.event package
When event occurs,event source
calls method in the listener
interface
Event source also passes an
event object to listener interface
Listener interfaces contain many
methods to handle the events
List of Event Listener Interfaces
ActionListener
List of Interfaces
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
WindowListener
ActionListener Interface
ActionListener interface has one method for processing (handling) the event
void actionPerformed(ActionEvent ae) - this method is called (invoked) when
action event occurs
Where ae = object of ActionEvent class is passed to method
AdjustmentListener Interface
AdjustmentListener interface has one method for processing (handling) the event
void adjusmentValueChanged(AdjustmentEvent ae) - this method is called
(invoked) when adjustment event occurs
Where ae = object of AdjustmentEvent class is passed to the method
ComponentListener Interface
ComponentListener interface has four methods for processing (handling) the
event
void componentResized(ComponentEvent ce) - this method is called (used) when
component is resized
Where ce = object of ComponentEvent class is passed to the method
void componentMoved(ComponentEvent ce) - this method is called (used) when
component is moved
void componentShown(ComponentEvent ce) - this method is called (used) when
component is shown or visible
void componentHidden(ComponentEvent ce) - this method is called (used) when
component is hidden or not visible
ContainerListener Interface
ContainerListener interface has two methods for processing (handling) the event
Where ce = object of ContainerEvent class is passed to the method
void componentAdded(ContainerEvent ce) - this method is called (used) when a
component is added to the container
void componentRemoved(ContainerEvent ce) - this method is called (used) when a
component is removed from the container
FocusListener Interface
FocusListener interface has two methods for processing (handling) the event
Where fe = object of FocusEvent class is passed to the method
void focusGained(FocusEvent fe) - this method is called (used) when a component
gets keyboard focus
void focusLost(FocusEvent fe) - this method is called (used) when a component
loses keyboard focus
ItemListener Interface
ItemListener interface has one methods for processing (handling) the event
Where ie = object of ItemEvent class is passed to the method
void itemStateChanged(ItemEvent ie) - this method is called (used) when state of
the item changes
KeyListener Interface
KeyListener interface has three methods for processing (handling) the event
Where ke = object of KeyEvent class is passed to the method
void keyPressed(KeyEvent ke) - this method is called (used) when key is pressed
void keyReleased(KeyEvent ke) - this method is called (used) when key is released
void keyTyped(KeyEvent ke) - this method is called (used) when we type any
character (apbhabets, numbers, symbols etc.) from the keyboard
When we press a character key like 'B' key then three key events are generatedin
sequence they are - key pressed, key typed and key released events
Similarly when we press a non-character key like 'SHIFT' key then two key events
are generated in sequence they are - key pressed and key released events
MouseListener Interface
MouseListener interface has five methods for processing (handling) the event
void mouseClicked(MouseEvent me) - this method is called (used) when mouse is
pressed and released immediately i.e clicked
void mouseEntered(MouseEvent me) - this method is called (used) when mouse
enters a component like textfield, button etc.
void mouseExited(MouseEvent me) - this method is called (used) when mouse
moves away from a component like textfield, button etc.
void mousePressed(MouseEvent me) - this method is called (used) when mouse is
pressed
void mouseReleased(MouseEvent me) - this method is called (used) when mouse is
released
MouseListener Interface
Where me = object of MouseEvent class is passed to the method
mouse is clicked
void mouseMoved(MouseEvent me) - this method is called many times when the
mouse is moved
void mouseDragged(MouseEvent me) - this method is called many times when the
mouse is dragged
MouseMotionListener interface has two methods for processing (handling) the
event
MouseMotionListener Interface
Where me = object of MouseEvent class is passed to the method
mouse is moved or
dragged
void mouseWheelMoved(MouseWheelEvent mwe) - thi method is called (used)
when mouse wheel is moved
MouseWheelListener interface has one method for processing (handling) the
event
MouseWheelListener Interface
Where mwe = object of MouseWheelEvent class is passed to the method
mouse wheel is
moved
void textChanged(TextEvent te) - this method is called (used) when there is change
in textfield or text area
TextListener interface has one method for processing (handling) the event
TextListener Interface
Where te = object of TextEvent class is passed to the method
void windowGainedFocus(WindowEvent we) - this method is called (used) when
window gets input focus
WindowFocusListener interface has two methods for processing (handling) the
event
WindowFocusListener Interface
Where we = object of WindowEvent class is passed to the method
void windowLostFocus(WindowEvent we) - this method is called (used) when
window losses input focus
void windowActivated(WindowEvent we) - this method is called (used) when
window is activated that is when window comes foreground or when it first
appears
WindowListener interface has seven methods for processing (handling) the event
WindowListener Interface
void windowClosed(WindowEvent we) - this method is called (used) when window
is closed
void windowClosing(WindowEvent we) - this method is called (used) when window
is closing
void windowDeactivated(WindowEvent we) - this method is called (used) when
window is deactivated that is window moves to background
WindowListener Interface
void windowIconified(WindowEvent we) - this method is called (used) when
window is changed from normal state to minimize state, minimized window is
displayed as icon
void windowOpened(WindowEvent we) - this method is called (used) when
window is shown for the first time
void deiconified(WindowEvent we) - this method is called (used) when window is
changed from minimize state to normal state
Delegation Event Model - How to develop event handling programs ?
Create GUI components like button,texfield,list,checkbox,label etc.
Register components for event listeners (addActionListener for
buttons, addMouseListener for mouse events etc.)
Inherit appropriate Listener interface for matching events (
TextListener for TextEvents, ItemListener for ItemEvent etc.)
Implement methods of Listener interface for event processing
(actionPerformed() method of ActionListener etc.
Steps for developing event handling programs
Program of ActionEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ActionEventExample" width=300 height=180>
</applet>
*/
public class ActionEventExample extends Applet implements
ActionListener
{
List obj1;
Button reset,submit;
String msg1 = "";
String msg2 = "";
public void init()
{
obj1 = new List(4,false);
obj1.add("First Sem");
obj1.add("Second Sem");
obj1.add("Third Sem");
obj1.add("Fourth Sem");
obj1.add("Fifth Sem");
submit = new Button("Submit");
add(obj1);
add(submit);
obj1.addActionListener(this);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
msg2 = ae.getActionCommand();
repaint();
}
// Show current selections.
public void paint(Graphics g) {
msg1 = "You have selected : ";
msg1 += obj1.getSelectedItem();
g.drawString(msg1,10,120);
if(msg2=="Submit")
{
msg2 = "Your data is submitted";
g.drawString(msg2, 6, 140);
}
}
}
Output of ActionEvent Program
Before Event After Event
Program of ItemEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ItemEventExample" width=300 height=180>
</applet>
*/
public class ItemEventExample extends Applet implements
ItemListener
{
Checkbox obj1,obj2,obj3;
String msg = "";
public void init()
{
obj1 = new Checkbox("Computer");
obj2 = new Checkbox("Mechanical");
obj3 = new Checkbox("Electrical");
add(obj1);
add(obj2);
add(obj3);
obj1.addItemListener(this);
obj2.addItemListener(this);
obj3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
public void paint(Graphics g) {
if(obj1.getState()==true)
{
msg = "You branch is "+obj1.getLabel();
g.drawString(msg, 6, 140);
}
if(obj2.getState()==true)
{
msg = "Your branch is "+obj2.getLabel();
g.drawString(msg, 6, 140);
}
if(obj3.getState()==true)
{
msg = "You branch is "+obj3.getLabel();
g.drawString(msg, 6, 140);
}
}
}
Output of ItemEvent Program
Before Event After Event
Program of TextEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="TextEventExample" width=300 height=180>
</applet>
*/
public class TextEventExample extends Applet implements
ActionListener,TextListener
{
Label L;
TextField obj;
String msg1 = "";
String msg2 = "";
public void init()
{
L = new Label("Name");
obj = new TextField(30);
add(L);
add(obj);
obj.addActionListener(this);
obj.addTextListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void textChanged(TextEvent te)
{
msg2 = "You have changed the text in textfield !";
repaint();
}
public void textValueChanged(TextEvent te)
{
msg2 = "Text value is changed in textfield !";
repaint();
}
public void paint(Graphics g)
{
msg1 = "Name: "+obj.getText();
g.drawString(msg1,5,120);
g.drawString(msg2,8,180);
}
}
Program of AdjustmentEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AdjustmentEventExample" width=300 height=180>
</applet>
*/
public class AdjustmentEventExample extends Applet implements
AdjustmentListener
{
Scrollbar obj1,obj2;
String msg="";
public void init()
{
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
obj1 = new Scrollbar(Scrollbar.VERTICAL,0,1,0,height);
obj2 = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,width);
add(obj1);
add(obj2);
obj1.addAdjustmentListener(this);
obj2.addAdjustmentListener(this);
}
public void
adjustmentValueChanged(AdjustmentEvent ae)
{
msg = "Scroll bar is adjusted";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,8,180);
}
}
Output of AdjustmentEvent Program
Before Event After Event
Program of FocusEvent
mport java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="FocusEventExample" width=300 height=180>
</applet>
*/
public class FocusEventExample extends Applet implements
FocusListener
{
Label L;
TextField obj;
Button submit;
String msg = "";
public void init()
{
L = new Label("Name");
obj = new TextField("textfield",30);
submit = new Button("Submit");
add(L);
add(obj);
add(submit);
obj.addFocusListener(this);
requestFocus();
}
public void focusGained(FocusEvent fe)
{
msg = "Component "+obj.getText()+" has gained focus";
repaint();
}
public void focusLost(FocusEvent fe)
{
msg = "Component "+obj.getText()+" has lost focus";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,8,180);
}
}
Output of FocusEvent Program
Before Event After Event
Program of KeyEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="KeyEventExample" width=300
height=180>
</applet>
*/
public class KeyEventExample extends Applet
implements KeyListener
{
String msg = "";
int x=10,y=90;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
msg = "You have pressed the key";
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("You have released the key");
}
public void keyTyped(KeyEvent ke)
{
msg = "You have pressed "+ke.getKeyChar()+"
key";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Output of KeyEvent Program
Before Event After Event
Program of MouseEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseEventExample" width=300
height=180>
</applet>
*/
public class MouseEventExample extends Applet
implements MouseListener
{
String msg = "";
int x=10,y=50;
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=10;
y=50;
msg = "You have clicked the mouse";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=10;
y=50;
msg = "Mouse entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;
y=50;
msg = "Mouse has exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg = "Mouse is pressed at "+x+" and "+y+" position";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg = "Mouse is released";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Output of MouseEvent Program
Before Event After Event
Program of MouseMotionEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseMotionEventExample"
width=300 height=180>
</applet>
*/
public class MouseMotionEventExample extends
Applet implements MouseMotionListener
{
String msg = "";
int x=10,y=50;
public void init()
{
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg = "Mouse is dragged at "+x+","+y+" psoition";
repaint();
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
showStatus("Mouse is moving at "+x+","+y+"
position");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Output of MouseMotionEvent Program
Before Event After Event
Program of MouseWheelEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseWheelEventExample"
width=300 height=180>
</applet>
*/
public class MouseWheelEventExample extends
Applet implements MouseWheelListener
{
String msg = "";
int x=10,y=50;
public void init()
{
addMouseWheelListener(this);
}
public void
mouseWheelMoved(MouseWheelEvent mwe)
{
msg = "Mouse wheel is moving";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Adapter classes
Java provides type of classes called as adapter classes which allows to process only
some events and not all events of a particular event listener
Adapter classes provides empty implementation of all methods in event listener
interfaces
For processing event using adapter classes, we have to :
Create a new class
Inherit one of the adapter classes
Implement only those methods or event in which we are intereseted
For example, KeyListener interface has three events - key pressed, key
released, and key typed, but we are only interested in key pressed event then
we can use KeyAdapter class in place of KeyListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionListener
WindowAdapter WindowListener
Listener Interfaced implementedby Adapter clases
MouseMotionAdapter
Adapter
Classes
Listener
Interfaces
Program of Adapter classes
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AdapterExample" width=300
height=180>
</applet>
*/
public class AdapterExample extends Applet
{
public void init()
{
addMouseListener(new
MouseAdapterExample(this));
}
}
class MouseAdapterExample extends
MouseAdapter
{
AdapterExample obj;
public MouseAdapterExample(AdapterExample obj)
{
this.obj = obj;
}
public void mouseClicked(MouseEvent me)
{
obj.showStatus("Mouse is clicked");
}
}
Output of Adapter Program
Before Event After Event
Inner classes
Inner classes are classes defined inside other classes or classes which are members
of another class
Inner classes are used to logically group together classes and interfaces
It makes the code more readable and maintainable
Inner classes can use the data members and functions (methods) of outer class,
including private data members and functions
Due to inner classes we have to write less code
Inner classes
class A ( outer class)
{
}
class B( inner class)
{
}
Fig. Inner class and outer class
Anonymous Inner classes
Anonymous inner classes are those inner classes which are not given names
Example :
import java.applet.*;
import java.awt.event.*;
public class AnonymousExample extends Applet
{
public void init( )
{
addKeyListener( new KeyAdapter( ) {
public void keyPressed(KeyEvent ke) {
showStatus("the key is pressed");
}
} );
}
}
inner class definition
without name
Activity Time
Assessment Test
Program Assignment
Group Discussion
Supplemental
Video
https://nptel.ac.in/courses/106/105/1
06105191/
Additional Resources
https://www.tutorialspoint.com/java
https://www.javatpoint.com/free-java-
projects
Summary of Class
Lesson Recap 1
Delegation
Event Model
Lesson Recap 2
AWT/Swing
components to
handle event
21
Lesson Recap 4
Inner classes
4
Lesson Recap 3
Adapter
classes
3
References
The Complete Reference Java Seventh Edition - Herbert
Schildt,McGraw Hill Publication
Thank You
For Attending!

More Related Content

What's hot (20)

Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java threads
Java threadsJava threads
Java threads
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Interface in java
Interface in javaInterface in java
Interface in java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Applets
AppletsApplets
Applets
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Android intents
Android intentsAndroid intents
Android intents
 

Similar to Unit-3 event handling

Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03Ankit Dubey
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVASrajan Shukla
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
Event handling
Event handlingEvent handling
Event handlingswapnac12
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5sotlsoc
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024kashyapneha2809
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.pptusama537223
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handlingteach4uin
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxGood657694
 

Similar to Unit-3 event handling (20)

Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Event handling
Event handlingEvent handling
Event handling
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Java gui event
Java gui eventJava gui event
Java gui event
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Event handling
Event handlingEvent handling
Event handling
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 
Module 5.pptx
Module 5.pptxModule 5.pptx
Module 5.pptx
 
Module3.11.pptx
Module3.11.pptxModule3.11.pptx
Module3.11.pptx
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 

More from Amol Gaikwad

IT Resources for Students.pdf
IT Resources for Students.pdfIT Resources for Students.pdf
IT Resources for Students.pdfAmol Gaikwad
 
Unit-IV Windowing and Clipping.pdf
Unit-IV Windowing and Clipping.pdfUnit-IV Windowing and Clipping.pdf
Unit-IV Windowing and Clipping.pdfAmol Gaikwad
 
How To Prepare Resume.pdf
How To Prepare Resume.pdfHow To Prepare Resume.pdf
How To Prepare Resume.pdfAmol Gaikwad
 
Unit-3 overview of transformations
Unit-3 overview of transformationsUnit-3 overview of transformations
Unit-3 overview of transformationsAmol Gaikwad
 
Unit 1 संगणक प्रणाली ( computer system ) ची ओळख
Unit 1 संगणक प्रणाली ( computer system ) ची ओळखUnit 1 संगणक प्रणाली ( computer system ) ची ओळख
Unit 1 संगणक प्रणाली ( computer system ) ची ओळखAmol Gaikwad
 
Unit-4 networking basics in java
Unit-4 networking basics in javaUnit-4 networking basics in java
Unit-4 networking basics in javaAmol Gaikwad
 
Unit-2 raster scan graphics,line,circle and polygon algorithms
Unit-2 raster scan graphics,line,circle and polygon algorithmsUnit-2 raster scan graphics,line,circle and polygon algorithms
Unit-2 raster scan graphics,line,circle and polygon algorithmsAmol Gaikwad
 
Unit-2 swing and mvc architecture
Unit-2 swing and mvc architectureUnit-2 swing and mvc architecture
Unit-2 swing and mvc architectureAmol Gaikwad
 
Unit-1 basics of computer graphics
Unit-1 basics of computer graphicsUnit-1 basics of computer graphics
Unit-1 basics of computer graphicsAmol Gaikwad
 
Unit-1 awt advanced java programming
Unit-1 awt advanced java programmingUnit-1 awt advanced java programming
Unit-1 awt advanced java programmingAmol Gaikwad
 

More from Amol Gaikwad (10)

IT Resources for Students.pdf
IT Resources for Students.pdfIT Resources for Students.pdf
IT Resources for Students.pdf
 
Unit-IV Windowing and Clipping.pdf
Unit-IV Windowing and Clipping.pdfUnit-IV Windowing and Clipping.pdf
Unit-IV Windowing and Clipping.pdf
 
How To Prepare Resume.pdf
How To Prepare Resume.pdfHow To Prepare Resume.pdf
How To Prepare Resume.pdf
 
Unit-3 overview of transformations
Unit-3 overview of transformationsUnit-3 overview of transformations
Unit-3 overview of transformations
 
Unit 1 संगणक प्रणाली ( computer system ) ची ओळख
Unit 1 संगणक प्रणाली ( computer system ) ची ओळखUnit 1 संगणक प्रणाली ( computer system ) ची ओळख
Unit 1 संगणक प्रणाली ( computer system ) ची ओळख
 
Unit-4 networking basics in java
Unit-4 networking basics in javaUnit-4 networking basics in java
Unit-4 networking basics in java
 
Unit-2 raster scan graphics,line,circle and polygon algorithms
Unit-2 raster scan graphics,line,circle and polygon algorithmsUnit-2 raster scan graphics,line,circle and polygon algorithms
Unit-2 raster scan graphics,line,circle and polygon algorithms
 
Unit-2 swing and mvc architecture
Unit-2 swing and mvc architectureUnit-2 swing and mvc architecture
Unit-2 swing and mvc architecture
 
Unit-1 basics of computer graphics
Unit-1 basics of computer graphicsUnit-1 basics of computer graphics
Unit-1 basics of computer graphics
 
Unit-1 awt advanced java programming
Unit-1 awt advanced java programmingUnit-1 awt advanced java programming
Unit-1 awt advanced java programming
 

Recently uploaded

Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...ssuserdfc773
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptAfnanAhmad53
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information SystemsAnge Felix NSANZIYERA
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)ChandrakantDivate1
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesChandrakantDivate1
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...ppkakm
 

Recently uploaded (20)

Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information Systems
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To Curves
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 

Unit-3 event handling

  • 1. Advanced Java Programming by Amol S. Gaikwad Lecturer, Government Polytechnic Gadchiroli Maharashtra
  • 3. Welcome! Are you excited for a fun learning session?
  • 4. Unit Outcomes Use delegation event model to develop event driven program for the given problem Use relevant AWT/Swing component to handle the given event Use adapter classes in java program to solve the given problem Use inner classes in java program to solve the given problem
  • 5. Introduction to Events Events are an important part of applet programming Applets are controlled by events Events are generated by variety of sources such as : user keyboard mouse
  • 6. Introduction to Events Events are generated by variety of sources such as : Various controls buttons checkbox choice list textfield textarea etc. For handling events java.awt.event package is used
  • 7. Delegation Event Model Delegation event model is a modern approach for handling events In this model there is a source, which generates event and there is listener which receives the event from the source The listener waits for the event and process the event when it is recieved This seperates the logic of user interface and application logic that processes the event In this model, the listener must register with source for receiving event notification Due to this only that listener receives event which want to receive and process it
  • 8. What is Event ? In delegation event model, an event is an object which contains all the information about change of state of source of event Events are generated when user interacts with graphical user interface (GUI ) It is also generated when user presses button, or key on keyboard or selects option from list, choice, checkbox etc. There are also other indirect sources of events, which are not caused by interaction of user with graphical user interface (GUI) Fig: GUI
  • 9. Other indirect sources of events are as follow : What is Event ? timer: when time expires counter : when count reaches a value software : when software failure occurs hardware : when hardware failure occurs
  • 10. In java, source of an event is an object which generates an event What is Event ? When state of source of an object changes it generates an event Source can generate more than one type of event A source should register the listeners, so that the listener can get notification of event The general form of registration for an event is written as : public void addTypeListener(TypeListener el) Where, Type = name of event el = reference to event listener
  • 11. For example, if we want to register listener for keyboard event then we can write as - addKeyListener( ), Similarly, for registering listener for mouse motion, we can write as - addMouseMotionListener( ) What is Event ? When all registered listeners are notified and receives copy of event object it is called as multicasting Some sources of events allows only one listener to register, the general form of such methods is as below : public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException When only one listener is notified of event it is called as unicasting
  • 12. What is Event ? Source of an event is also provides a method for removing or unregistering listener, the syntax of the method is given as below: public void removeTypeListener(TypeListener el) For example, the method for removing or unregistering keyboard listener is written as : removeKeyListener( ); Component class provides methods (functions) to add and remove keyboard and mouse event listeners
  • 13. Event Listeners Listeners are objects that receives notification when an event occurs A listener must be register with one or more source to receive notification of an event It should have methods (functions) to receive and process the event notification Methods that receive and process events are defined (found) in a group of interfaces in java.awt.event package
  • 14. Event Classes In java there are classes that represents events, such classes are called as Event classes EventObject class is a root class of java's event class heirarchy EventObject class is present in java.util package It is super class (top most class) for all types of events Constructor EventObject(Object src), where src = object that generates the event Methods (functions) of EvenObject class : getSource( ) - returns source of event toString( ) - returns string description of event
  • 15. Event Classes The AWTEvent class is superclass (top most class) of all AWT-based events used by delegation event model The AWTEvent class is present in java.awt package, it is subclass (child class) of EventObject class int getID( ) - tells type of event java.awt.event package describes several types of events
  • 18. ActionEvent Class ActionEvent is created when - button is pressed, list item is double clicked or menu item is selected ActionEvent has four integer constants : ALT_MASK = whether ALT key was pressed CTRL_MASK = whether CTRL key was pressed META_MASK = whether META key was pressed SHIFT_MASK = whether SHIFT key was pressed ActionEvent class has three constructors : ActionEvent(Object src,int type,String cmd) , ActionEvent( Object src,int type,String cmd,int modifiers) ActionEvent( Object src,int type,String cmd, long when, int modifiers)
  • 19. ActionEvent Class Where : src = reference to object that generated the event type = what type of event is cmd = command string of event modifier keys = ALT,CTRL,META or SHIFT keys were pressed or not when = when the event has occured String getActionCommand( ) - returns command name of event object int getModifiers( ) - returns which modifier key was pressed when event occured int getWhen( ) - returns the time when event occurs (timestamp)
  • 20. AdjustmentEvent Class AdjustmentEvent is created by scroll bar Five types of AdjustmentEvent are as follows : BLOCK_DECREMENT = when user clicks inside scroll bar to decrease its value BLOCK_INCREMENT = when user clicks inside scroll bar to increase its value TRACK = when the slider is dragged UNIT_DECREMENT = when button at the end of scroll bar is clicked to decrease it's value UNIT_INCREMENT = when button at the end of scroll bar is clicked to increase it's value
  • 21. AdjustmentEvent Class ADJUSTMENT_VALUE_CHANGED - tells whether change has occured or not AdjustmentEvent class has one constructor : AdjustmentEvent(Adjustable src, int id, int type, int data) Where src = reference to the object that generated the event id = ADJUSTMENT_VALUE_CHANGED type = type of event data = data related to the event Adjustable getAdjustable( ) - returns the object that generates the event int getAdjustmentType( ) - returns the type of adjusment events from five types of events int getValue( ) - returns how much scroll bar is changed
  • 22. ComponentEvent Class ComponentEvent is created when the size, position,or visibility of component is changed Four types of ComponentEvent indentified by integer constants are as follows : COMPONENT_HIDDEN = the component was hidden COMPONENT_MOVED = the component was moved COMPONENT_RESIZED = the component was resized COMPONENT_SHOWN= the component becomes visible
  • 23. ComponentEvent Class ComponentEvent class constructor : ComponentEvent(Component src, int type) ComponentEvent class is superclass (parent class) of ContainerEvent class, FocusEvent class, KeyEvent class, MouseEvent class ans WindowEvent class Component getComponent( ) - returns the component that generated the event
  • 24. ContainerEvent Class ContainerEvent is created when a component is added to or removed from a container Two types of ContainerEvent identified by integer constant are as follow : COMPONENT_ADDED = when component is added to the container COMPONENT_REMOVED = when component is removed from the container ContainerEvent class is subclass(child class) of ComponentEvent class ContainerEvent(Component src, int type, Component comp) src = reference to container that generated the event comp = component that is added or removed from the container type = type of event
  • 25. ContainerEvent Class Container getContainer( ) - returns reference to the container that generated this event Component getChild( ) - returns reference to the component that was added to or removed from the container
  • 26. FocusEvent Class FocusEvent is created when a component gets or loses input focus Three constructors of FocusEvent class are as follow : FocusEvent class is subclass(child class) of ComponentEvent class FocusEvent(Component src, int type) FocusEvent(Component src, int type, boolean temporaryFlag) FocusEvent(Component src, int type, boolean temporaryFlag, Component other) Where src = reference to component that generated the event type = type of event
  • 27. FocusEvent Class temoraryFlag has value true or false temoraryFlag has value true if the focus event is temporary otherwise false Suppose our focus is in a text field and move the mouse to adjust scroll bar then we called the focus is temporary lost the other component is a opposite component when focus changes When the event type is FOCUS_GAINED, the other component is that component which lost focus Similarly, when the event type is FOCUS_LOST, the other component is that component which gains focus
  • 28. FocusEvent Class Two types of Focus Event identified by integer constant are as follow : FOCUS_GAINED = when the component gains the input focus FOCUS_LOST = when the component loses the input focus Component getOppositeComponent( ) - this method returns the opposite component that got or lost the input focus boolean isTemporary( ) - this method returns whether the focus change is temporary or not, true means focus change is temporary
  • 29. ItemEvent Class An ItemEvent is created when - checkbox or list item is clicked, when checkable menu item is selected or deselected DESELECTED - when an item is deselected by the user Two types of ItemEvent identified by integer constant are as follow : SELECTED - when an item is selected by the user ITEM_STATE_CHANGED - this constant tells whether the state is changed or not ItemEvent( ItemSelectable src, int type, Object entry, int state) where src = the component that generated this event type = type of event
  • 30. ItemEvent Class Where entry = item of checkbox or list or checkable menu item that generated the event state = the current state of the item Object getItem( ) - this method returns reference to the item that generated the event ItemSelectable getItemSelectable( ) - this method returns reference to the itemSelectable object that generated the event List and Choice implements (inherits) ItemSelectable interface int getStateChange( ) - this method returns the changed state for an event
  • 31. KeyEvent Class KeyEvent is created when we give input from keyboard KeyEvent class is a subclass (child class) of InputEvent class Three types of KeyEvent identified by integer constant are as follow : KEY_PRESSED - when a key is pressed KEY_RELEASED - when a key is released KEY_TYPED - when a character is generated by typing a key There are some keys which when pressed do not generate character, like SHIFT key
  • 32. KeyEvent Class KeyEvent class has various integer constants which are as follow : VK_0 to VK_9 = ASCII value of numbers VK_A to VK_Z = ASCII value of letters Other integer constants are as follow : VK_ENTER VK_DOWN VK_PAGE_UP VK_ESCAPE VK_LEFT VK_SHIFT VK_CANCEL VK_RIGHT VK_ALT VK_UP VK_PAGE_DOWN VK_CONTROL VK constants means virtual key codes
  • 33. KeyEvent Class Constructors of KeyEvent class are as follow : KeyEvent(Component src, int type, long when, int modifiers, int code) KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) Where src = reference to component that generated the event type = type of event modifiers = which modifier key pressed (control,shift,alt) when key event occured code = VK_UP or VK_A code is passed here ch = character equivalent is passed here, if not present then CHAR_UNDEFINED is passed here when= system time when KeyEvent occured
  • 34. char getKeyChar( ) - returns the character that was entered, if valid character is available then it returns CHAR_UNDEFINED, int getKeyCode( ) - returns key code,when KEY_TYPED event occurs it returns VK_UNDEFINED KeyEvent Class
  • 35. MouseEvent Class MouseEvent is created when we interact with mouse Eight types of MouseEvent identified by integer constant are as follow : MOUSE_CLICKED = when the mouse is clicked by the user MOUSE_DRAGGED = when the mouse is dragged by the user MOUSE_ENTERED = when mouse enters a component MOUSE_EXITED = when mouse exits a component MOUSE_MOVED = when the mouse is moved MOUSE_PRESSED = when the mouse is pressed MOUSE_RELEASED = when the mouse is released MOUSE_WHEEL = when the mouse wheel is moved
  • 36. MouseEvent Class MouseEvent class is subclass (child class) of InputEvent class MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup) Where src = reference to component that generated the event type = type of event when= system time when MouseEvent occured modifiers = which modifier key pressed (control,shift,alt) when mouse event occured x, y = x and y coordinates of mouse position triggersPopup = whether pop up menu appears in this mouse event
  • 37. MouseEvent Class int getX( ) - returns x coordinate of mouse position when event occured int getY( ) - returns y coordinate of mouse position when event occured Point getPoint( ) - returns Point object containing x and y coordinates of mouse void translatePoint(int x, int y) - changes the location of mouse event by adding x and y to the old coordinates of mouse event int getClickCount( ) - number of times mouse is clicked in this event boolean inPopupTrigger( ) - whether this mouse event causes popup menu to appear int getButton( ) - returns a value that tells which button caused the event, the value can be constants like - NOBUTTON, BUTTON1, BUTTON2, BUTTON3
  • 38. MouseWheelEvent Class MouseWheelEvent is created when we interact with mouse wheel MouseWheelEvent class is subclass (child class) of MouseEvent class Two types of MouseWheelEvent identified by integer constant are as follow : WHEEL_BLOCK_SCROLL= when page-up or page-down scroll event occurs Mouse wheels are used for scrolling WHEEL_UNIT_SCROLL= when line-up or line-down scroll event occurs MouseWheelEvent( Component src, int type, long when, int modifiers, intx, int y, int clicks, boolean triggrtPopup, int scrollHow, int amount, int count)
  • 39. MouseWheelEvent Class Where src = reference to component that generated the event type = type of event when= system time when MouseEvent occured modifiers = which modifier key pressed (control,shift,alt) when mouse event occured x, y = x and y coordinates of mouse position triggersPopup = whether pop up menu appears in this mouse event scrollHow = constants WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL amounts = number of units to scroll count = number of rotations the wheel of mouse has done
  • 40. MouseWheelEvent Class int getWheelRotation( ) - returns the number of rotations the mouse wheel has done int getScrollTypes( ) - returns typeof scroll whether WHEEL_UNIT_SCROLL type or WHEEL_BLOCK_SCROLL type int getScrollAmount( ) - if scoll type is WHEEL_UNIT_SCROLL, then this function returns the number of units to scroll
  • 41. TextEvent Class TextEvents are created when user or program enters some characters in text fields or text areas TextEvent class has a one integer constant TEXT_VALUE_CHANGED TextEvent class has one constructor which is as follow : TextEvent( Object src, int type) Where src = reference to object that generated the event type = type of event
  • 42. WindowEvent Class WindowEvents are created when we interact with windows WINDOW_ACTIVATED = when window is activated Ten types of WindowEvent identified by integer constant are as follow : WINDOW_CLOSED = when window is closed WINDOW_CLOSING = when user requests to close the window WINDOW_DEACTIVATED = when the window is deactivated WINDOW_DEICONIFIED = when the window is deiconified WINDOW_LOS_FOCUS = when the window loses the input focus WINDOW_LOS_OPENED = when the window is opened WINDOW_STATE_CHANGED = when the state of window is changed
  • 43. WindowEvent Class WindowEvents class is subclass (child class) of ComponentEvent class WindowEvent( Window src, int type) The constructors of WindowEvent class are as follow : WindowEvent( Window src, int type, Window other) WindowEvent( Window src, int type, int fromstate, int tostate) WindowEvent( Window src, int type, Window other, int fromstate, int tostate Where src = reference to object that generated the event type = type of event other = opposite window when focus event occurs
  • 44. WindowEvent Class fromstate = previous state of window tostate = new state of window, when window changes its state Window getWindow( ) - returns Window object that generated the event Window getOppositeWindow( ) - returns opposite window when focus event occurs int getOldState( ) - returns the previous state (old state) of window int getNewState( ) - returns the new state of window
  • 45. Event Listener Interfaces Delegation Event Model Listener Interfaces sources and listeners are two parts of delegation event model of event handling Listeners are created by implementing (inheriting) one or more interfaces Listener interfaces are present in java.awt.event package When event occurs,event source calls method in the listener interface Event source also passes an event object to listener interface Listener interfaces contain many methods to handle the events
  • 46. List of Event Listener Interfaces ActionListener List of Interfaces AdjustmentListener ComponentListener ContainerListener FocusListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener
  • 47. ActionListener Interface ActionListener interface has one method for processing (handling) the event void actionPerformed(ActionEvent ae) - this method is called (invoked) when action event occurs Where ae = object of ActionEvent class is passed to method
  • 48. AdjustmentListener Interface AdjustmentListener interface has one method for processing (handling) the event void adjusmentValueChanged(AdjustmentEvent ae) - this method is called (invoked) when adjustment event occurs Where ae = object of AdjustmentEvent class is passed to the method
  • 49. ComponentListener Interface ComponentListener interface has four methods for processing (handling) the event void componentResized(ComponentEvent ce) - this method is called (used) when component is resized Where ce = object of ComponentEvent class is passed to the method void componentMoved(ComponentEvent ce) - this method is called (used) when component is moved void componentShown(ComponentEvent ce) - this method is called (used) when component is shown or visible void componentHidden(ComponentEvent ce) - this method is called (used) when component is hidden or not visible
  • 50. ContainerListener Interface ContainerListener interface has two methods for processing (handling) the event Where ce = object of ContainerEvent class is passed to the method void componentAdded(ContainerEvent ce) - this method is called (used) when a component is added to the container void componentRemoved(ContainerEvent ce) - this method is called (used) when a component is removed from the container
  • 51. FocusListener Interface FocusListener interface has two methods for processing (handling) the event Where fe = object of FocusEvent class is passed to the method void focusGained(FocusEvent fe) - this method is called (used) when a component gets keyboard focus void focusLost(FocusEvent fe) - this method is called (used) when a component loses keyboard focus
  • 52. ItemListener Interface ItemListener interface has one methods for processing (handling) the event Where ie = object of ItemEvent class is passed to the method void itemStateChanged(ItemEvent ie) - this method is called (used) when state of the item changes
  • 53. KeyListener Interface KeyListener interface has three methods for processing (handling) the event Where ke = object of KeyEvent class is passed to the method void keyPressed(KeyEvent ke) - this method is called (used) when key is pressed void keyReleased(KeyEvent ke) - this method is called (used) when key is released void keyTyped(KeyEvent ke) - this method is called (used) when we type any character (apbhabets, numbers, symbols etc.) from the keyboard When we press a character key like 'B' key then three key events are generatedin sequence they are - key pressed, key typed and key released events Similarly when we press a non-character key like 'SHIFT' key then two key events are generated in sequence they are - key pressed and key released events
  • 54. MouseListener Interface MouseListener interface has five methods for processing (handling) the event void mouseClicked(MouseEvent me) - this method is called (used) when mouse is pressed and released immediately i.e clicked void mouseEntered(MouseEvent me) - this method is called (used) when mouse enters a component like textfield, button etc. void mouseExited(MouseEvent me) - this method is called (used) when mouse moves away from a component like textfield, button etc.
  • 55. void mousePressed(MouseEvent me) - this method is called (used) when mouse is pressed void mouseReleased(MouseEvent me) - this method is called (used) when mouse is released MouseListener Interface Where me = object of MouseEvent class is passed to the method mouse is clicked
  • 56. void mouseMoved(MouseEvent me) - this method is called many times when the mouse is moved void mouseDragged(MouseEvent me) - this method is called many times when the mouse is dragged MouseMotionListener interface has two methods for processing (handling) the event MouseMotionListener Interface Where me = object of MouseEvent class is passed to the method mouse is moved or dragged
  • 57. void mouseWheelMoved(MouseWheelEvent mwe) - thi method is called (used) when mouse wheel is moved MouseWheelListener interface has one method for processing (handling) the event MouseWheelListener Interface Where mwe = object of MouseWheelEvent class is passed to the method mouse wheel is moved
  • 58. void textChanged(TextEvent te) - this method is called (used) when there is change in textfield or text area TextListener interface has one method for processing (handling) the event TextListener Interface Where te = object of TextEvent class is passed to the method
  • 59. void windowGainedFocus(WindowEvent we) - this method is called (used) when window gets input focus WindowFocusListener interface has two methods for processing (handling) the event WindowFocusListener Interface Where we = object of WindowEvent class is passed to the method void windowLostFocus(WindowEvent we) - this method is called (used) when window losses input focus
  • 60. void windowActivated(WindowEvent we) - this method is called (used) when window is activated that is when window comes foreground or when it first appears WindowListener interface has seven methods for processing (handling) the event WindowListener Interface void windowClosed(WindowEvent we) - this method is called (used) when window is closed void windowClosing(WindowEvent we) - this method is called (used) when window is closing void windowDeactivated(WindowEvent we) - this method is called (used) when window is deactivated that is window moves to background
  • 61. WindowListener Interface void windowIconified(WindowEvent we) - this method is called (used) when window is changed from normal state to minimize state, minimized window is displayed as icon void windowOpened(WindowEvent we) - this method is called (used) when window is shown for the first time void deiconified(WindowEvent we) - this method is called (used) when window is changed from minimize state to normal state
  • 62. Delegation Event Model - How to develop event handling programs ? Create GUI components like button,texfield,list,checkbox,label etc. Register components for event listeners (addActionListener for buttons, addMouseListener for mouse events etc.) Inherit appropriate Listener interface for matching events ( TextListener for TextEvents, ItemListener for ItemEvent etc.) Implement methods of Listener interface for event processing (actionPerformed() method of ActionListener etc. Steps for developing event handling programs
  • 63. Program of ActionEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="ActionEventExample" width=300 height=180> </applet> */ public class ActionEventExample extends Applet implements ActionListener { List obj1; Button reset,submit; String msg1 = ""; String msg2 = ""; public void init() { obj1 = new List(4,false); obj1.add("First Sem"); obj1.add("Second Sem"); obj1.add("Third Sem"); obj1.add("Fourth Sem"); obj1.add("Fifth Sem"); submit = new Button("Submit"); add(obj1); add(submit); obj1.addActionListener(this); submit.addActionListener(this); } public void actionPerformed(ActionEvent ae) { msg2 = ae.getActionCommand(); repaint(); } // Show current selections. public void paint(Graphics g) { msg1 = "You have selected : "; msg1 += obj1.getSelectedItem(); g.drawString(msg1,10,120); if(msg2=="Submit") { msg2 = "Your data is submitted"; g.drawString(msg2, 6, 140); } } }
  • 64. Output of ActionEvent Program Before Event After Event
  • 65. Program of ItemEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="ItemEventExample" width=300 height=180> </applet> */ public class ItemEventExample extends Applet implements ItemListener { Checkbox obj1,obj2,obj3; String msg = ""; public void init() { obj1 = new Checkbox("Computer"); obj2 = new Checkbox("Mechanical"); obj3 = new Checkbox("Electrical"); add(obj1); add(obj2); add(obj3); obj1.addItemListener(this); obj2.addItemListener(this); obj3.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { if(obj1.getState()==true) { msg = "You branch is "+obj1.getLabel(); g.drawString(msg, 6, 140); } if(obj2.getState()==true) { msg = "Your branch is "+obj2.getLabel(); g.drawString(msg, 6, 140); } if(obj3.getState()==true) { msg = "You branch is "+obj3.getLabel(); g.drawString(msg, 6, 140); } } }
  • 66. Output of ItemEvent Program Before Event After Event
  • 67. Program of TextEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="TextEventExample" width=300 height=180> </applet> */ public class TextEventExample extends Applet implements ActionListener,TextListener { Label L; TextField obj; String msg1 = ""; String msg2 = ""; public void init() { L = new Label("Name"); obj = new TextField(30); add(L); add(obj); obj.addActionListener(this); obj.addTextListener(this); } public void actionPerformed(ActionEvent ae) { repaint(); } public void textChanged(TextEvent te) { msg2 = "You have changed the text in textfield !"; repaint(); } public void textValueChanged(TextEvent te) { msg2 = "Text value is changed in textfield !"; repaint(); } public void paint(Graphics g) { msg1 = "Name: "+obj.getText(); g.drawString(msg1,5,120); g.drawString(msg2,8,180); } }
  • 68. Program of AdjustmentEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="AdjustmentEventExample" width=300 height=180> </applet> */ public class AdjustmentEventExample extends Applet implements AdjustmentListener { Scrollbar obj1,obj2; String msg=""; public void init() { int width = Integer.parseInt(getParameter("width")); int height = Integer.parseInt(getParameter("height")); obj1 = new Scrollbar(Scrollbar.VERTICAL,0,1,0,height); obj2 = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,width); add(obj1); add(obj2); obj1.addAdjustmentListener(this); obj2.addAdjustmentListener(this); } public void adjustmentValueChanged(AdjustmentEvent ae) { msg = "Scroll bar is adjusted"; repaint(); } public void paint(Graphics g) { g.drawString(msg,8,180); } }
  • 69. Output of AdjustmentEvent Program Before Event After Event
  • 70. Program of FocusEvent mport java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="FocusEventExample" width=300 height=180> </applet> */ public class FocusEventExample extends Applet implements FocusListener { Label L; TextField obj; Button submit; String msg = ""; public void init() { L = new Label("Name"); obj = new TextField("textfield",30); submit = new Button("Submit"); add(L); add(obj); add(submit); obj.addFocusListener(this); requestFocus(); } public void focusGained(FocusEvent fe) { msg = "Component "+obj.getText()+" has gained focus"; repaint(); } public void focusLost(FocusEvent fe) { msg = "Component "+obj.getText()+" has lost focus"; repaint(); } public void paint(Graphics g) { g.drawString(msg,8,180); } }
  • 71. Output of FocusEvent Program Before Event After Event
  • 72. Program of KeyEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="KeyEventExample" width=300 height=180> </applet> */ public class KeyEventExample extends Applet implements KeyListener { String msg = ""; int x=10,y=90; public void init() { addKeyListener(this); requestFocus(); } public void keyPressed(KeyEvent ke) { msg = "You have pressed the key"; repaint(); } public void keyReleased(KeyEvent ke) { showStatus("You have released the key"); } public void keyTyped(KeyEvent ke) { msg = "You have pressed "+ke.getKeyChar()+" key"; repaint(); } public void paint(Graphics g) { g.drawString(msg,x,y); } }
  • 73. Output of KeyEvent Program Before Event After Event
  • 74. Program of MouseEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="MouseEventExample" width=300 height=180> </applet> */ public class MouseEventExample extends Applet implements MouseListener { String msg = ""; int x=10,y=50; public void init() { addMouseListener(this); } public void mouseClicked(MouseEvent me) { x=10; y=50; msg = "You have clicked the mouse"; repaint(); } public void mouseEntered(MouseEvent me) { x=10; y=50; msg = "Mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { x=10; y=50; msg = "Mouse has exited"; repaint(); } public void mousePressed(MouseEvent me) { x=me.getX(); y=me.getY(); msg = "Mouse is pressed at "+x+" and "+y+" position"; repaint(); } public void mouseReleased(MouseEvent me) { x=me.getX(); y=me.getY(); msg = "Mouse is released"; repaint(); } public void paint(Graphics g) { g.drawString(msg,x,y); } }
  • 75. Output of MouseEvent Program Before Event After Event
  • 76. Program of MouseMotionEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="MouseMotionEventExample" width=300 height=180> </applet> */ public class MouseMotionEventExample extends Applet implements MouseMotionListener { String msg = ""; int x=10,y=50; public void init() { addMouseMotionListener(this); } public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg = "Mouse is dragged at "+x+","+y+" psoition"; repaint(); } public void mouseMoved(MouseEvent me) { x=me.getX(); y=me.getY(); showStatus("Mouse is moving at "+x+","+y+" position"); repaint(); } public void paint(Graphics g) { g.drawString(msg,x,y); } }
  • 77. Output of MouseMotionEvent Program Before Event After Event
  • 78. Program of MouseWheelEvent import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="MouseWheelEventExample" width=300 height=180> </applet> */ public class MouseWheelEventExample extends Applet implements MouseWheelListener { String msg = ""; int x=10,y=50; public void init() { addMouseWheelListener(this); } public void mouseWheelMoved(MouseWheelEvent mwe) { msg = "Mouse wheel is moving"; repaint(); } public void paint(Graphics g) { g.drawString(msg,x,y); } }
  • 79. Adapter classes Java provides type of classes called as adapter classes which allows to process only some events and not all events of a particular event listener Adapter classes provides empty implementation of all methods in event listener interfaces For processing event using adapter classes, we have to : Create a new class Inherit one of the adapter classes Implement only those methods or event in which we are intereseted For example, KeyListener interface has three events - key pressed, key released, and key typed, but we are only interested in key pressed event then we can use KeyAdapter class in place of KeyListener
  • 80. ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionListener WindowAdapter WindowListener Listener Interfaced implementedby Adapter clases MouseMotionAdapter Adapter Classes Listener Interfaces
  • 81. Program of Adapter classes import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="AdapterExample" width=300 height=180> </applet> */ public class AdapterExample extends Applet { public void init() { addMouseListener(new MouseAdapterExample(this)); } } class MouseAdapterExample extends MouseAdapter { AdapterExample obj; public MouseAdapterExample(AdapterExample obj) { this.obj = obj; } public void mouseClicked(MouseEvent me) { obj.showStatus("Mouse is clicked"); } }
  • 82. Output of Adapter Program Before Event After Event
  • 83. Inner classes Inner classes are classes defined inside other classes or classes which are members of another class Inner classes are used to logically group together classes and interfaces It makes the code more readable and maintainable Inner classes can use the data members and functions (methods) of outer class, including private data members and functions Due to inner classes we have to write less code
  • 84. Inner classes class A ( outer class) { } class B( inner class) { } Fig. Inner class and outer class
  • 85. Anonymous Inner classes Anonymous inner classes are those inner classes which are not given names Example : import java.applet.*; import java.awt.event.*; public class AnonymousExample extends Applet { public void init( ) { addKeyListener( new KeyAdapter( ) { public void keyPressed(KeyEvent ke) { showStatus("the key is pressed"); } } ); } } inner class definition without name
  • 86. Activity Time Assessment Test Program Assignment Group Discussion
  • 89. Summary of Class Lesson Recap 1 Delegation Event Model Lesson Recap 2 AWT/Swing components to handle event 21 Lesson Recap 4 Inner classes 4 Lesson Recap 3 Adapter classes 3
  • 90. References The Complete Reference Java Seventh Edition - Herbert Schildt,McGraw Hill Publication