SlideShare a Scribd company logo
SHARAD INSTITUTE OF TECHNOLOGY
COLLEGE OF ENGINEERING ,YADRAV
ADVANCED JAVA PROGRAMMING
UNIT : 3
Event Handling
Presented By : Mr. PRASHANT B.PATIL
DEPARTMENT OF COMPUTER & SCIENCE ENGINEERING
3. Event Handling
3.1. The delegation Event Model : Event sources, Event Listeners.
3.2. Event classes : the ActionEvent class, the ItemEvent class, the
KeyEvent class, the MouseEvent class, the TextEvent class, the
WindowEvent class.
3.3. Adapter classes.
3.4. Inner classes.
3.5. Event Listener Interfaces : Action Listener interface,
ItemListener interface, KeyListener interface, MouseListener
interface, TextListener interface, WindowListener interface.
What is an Event?
Change in the state of an object is known as event i.e. event
describes the change in state of source. Events are generated
as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes
an event to happen.
Types of Event :
The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct
interaction of user. They are generated as consequences of a
person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the
mouse, entering a character through keyboard,selecting an item
from list, scrolling the page etc.
2. Background Events - Events that don’t require interactions of
users to generate an event are known as background events.
Examples of these events are operating system failures/interrupts,
operation completion, etc
Introduction to Event Handling :
Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs. This
mechanism have the code which is known as event handler
that is executed when an event occurs. Java uses the
Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the
events.
3.1. The delegation Event Model :
The modern approach to handling events is based on
the delegation event model, which defines standard and
consistent mechanisms to generate and process events.
Its concept is quite simple, a source generates an event
and sends it to one or more listeners.
In this scheme, the listener simply waits until it
receives an event. Once an event is received, the
listener processes the event and then returns.
In the delegation event model, listeners must
register with a source in order to receive an event
notification.
This provides an important benefit: notifications are
sent only to listeners that want to receive them. This
is a more efficient way to handle events than the
design used by the original Java 1.0 approach.
In the delegation event model, The event model is
based on the Event Source and Event Listeners.
Event Source is any object which creates the
message / event. The Event Listener is an object that
receives the messages / events.
Advance java programming- Event handling
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. Here is the general form:
public void addTypeListener (TypeListener el )
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.
This is known as multicasting the event. In all
cases, notifications are sent only to listeners that
register to receive them.
Some sources may allow only one listener to
register. The general form of such a method is this:
public void addTypeListener(TypeListener el )
throws java.util.TooManyListenersException
Here, Type is the name of the event, and el is a
reference to the event listener. When such an event
occurs, the registered listener is notified. This is
known as unicasting the event.
A source must also provide a method that allows a listener to
unregister an interest in a specific type of event. The general form
of such a method is this:
public void removeTypeListener(TypeListener el )
Here, Type is the name of the event, and el is a reference to the
event listener. For example, to remove a keyboard listener, you
would call removeKeyListener( ).
The methods that add or remove listeners are provided by the
source that generates events. For example, the Component class
provides methods to add and remove keyboard and mouse event
listeners.
• 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 methods that receive and process events are defined in a
set of interfaces, such as those found in java.awt.event. For
example, ActionListener, ItemListener, KeyListener
MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
3.2. Event classes :
• Event classes are the responsible for handling
events in the event handling mechanism.
• All the listeners and its methods are also
encapsulated with event classes.
• All the event classes are present under
java.awt.event package.
• EventObject class it is the root class from which
all event state objects shall be derived.
• It is the superclass of all events.
• All events are constructed with a reference to the object.
• The EventObject class is at the top/root of the Java
event class hierarchy.
EventObject class constructor is:
EventObject (Object src)
• Here, src is the objects that generates the event.
EventObject class Methods :
The getSource() and toString() are the methods of the EventObject class.
1. getSource( )
The getSource( ) method returns the source of the event.
• Its general form is shown here:
Object getSource( )
The getSource method is used in the actionPerformed method to determine
which button was clicked.
2. toString( )
toString( ) returns the string equivalent of the event.
The toString() method returns the String representation of the object.
If you want to represent any object as a string
If you print any object, Java compiler internally invokes the toString() method
on the object.
• There is getID( ) method belonging to java.awt.event
package returns the nature of the event. Or can be used to
determine the type of the event.
• Syntax is,
int getID( )
• getId() method returns the identifier of this Thread. The
thread ID is a positive long number generated when this
thread was created. The thread ID is unique and remains
unchanged during its lifetime. When a thread is
terminated, this thread ID may be reused
Event classes :
1. ActionEvent Class.
2. ItemEvent Class.
3. KeyEvent Class.
4. MouseEvent Class.
5. TextEvent Class.
6. WindowEvent Class.
1. ActionEvent Class :
An action event occurs, whenever an action is performed by the user.
Examples: When the user clicks a button, chooses a menu item, presses
Enter in a text field. The result is that an actionPerformed message is sent to
all action listeners that are registered on the relevant component.
An instance of the ActionEvent class is passed to the ActionListener when
an action event occurs. You can use this object to determine information
about the event.
actionPerformed() method
The actionPerformed() method is invoked automatically whenever
you click on the registered component.
ActionEvent constructor :
ActionEvent (Object src)
1. Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
2. Override the actionPerformed() method:
public void actionPerformed(ActionEvent e)
{
//Write the code here
}
ActionEvent Methods:
1. String getActionCommand() :
This method is useful for obtaining the
Command string which is specified during the
generation of event.
Returns the object on which the event occurred.
2. int getWhen() :
The getWhen() method returns the time at
which the event occurs.
2. ItemEvent Class :
There are two types of item events which are
identified by two integer constants :
ItemEvent defiens one integer constant,
ITEM_STATE_CHANGED that signifies a change of state.
DESELECTED The user deselected an item.
SELECTED The user selected an item.
ItemEvent Methods :
1. The getItem() :
returns a reference to the item that generated an
event.
2. ItemSelectable getItemSelectable() :
The getItemSelectable() method returns a reference
to the ItemSelectable object that generated an event.
3. Int getStateChange() :
The getStateChange() method returns the state
change(i.e, SELECTED or DESELECTED) for an event.
Advance java programming- Event handling
3. KeyEvent Class :
• This event is generated when key on the keyboard is
pressed or released.
• There are three types of key events, which are identified by
these integer constants: KEY_PRESSED,
KEY_RELEASED, and
KEY_TYPED.
• The first two events are generated when a key is pressed or
released.
• The last event occurs when a character is generated.
Many other integer constants that are defined by
The VK constants specifies virtual key codes.
For example, pressing the Shift key will cause a KEY_PRESSED
event with a VK_SHIFT keyCode, while pressing the 'a' key will
result in a VK_A keyCode. After the 'a' key is released, a
KEY_RELEASED event will be fired with VK_A. Separately, a
KEY_TYPED event with a keyChar value of 'A' is generated
VK_ALT VK_DOWN VK_LEFT VK_RIGHT
VK_CANCLE VK_ENTER VK_ PAGE_DOWN VK_SHIFT
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP
Constructor of Keyevent Class :
1. KeyEvent (Component src)
Here,
• src is a reference to the object that generated this
event.
• KeyEvent is a subclass of InputEvent
KeyEvent Methods :
1. char getKeyChar ()
The getKeyChar() method returns the character that was
entered.
public void keyTyped(KeyEvent ke) {
char keyChar = ke.getKeyChar();
if (keyChar == 'a') {
System.out.println("You typed 'a'");
}
2. int getKeyCode ()
getKeyCode() method returns the key code.
public void keyPressed(KeyEvent ke) {
int keyCode = ke.getKeyCode();
if (keyCode == 66) {
System.out.println("You Typed b");
}
}
// adding the KeyListener to the text area
obj.addKeyListener(this);
• public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
• public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
• public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
4. MouseEvent Class :
This event occurs when mouse action occurs on a component. It reacts
for both mouse event and mouse motion event.
Mouse Events :
A mouse button is pressed
A mouse button is released
A mouse button is clicked (pressed or released)
The mouse cursor enters a component
The mouse cursor exits a component
Mouse Motion Events :
The mouse is moved
The mouse is dragged
There are seven types of mouse events.
MouseEvent class defines the following integer
constants:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MouseEvent class is a subclass of InputEvent. It uses the
constructor:
MouseEvent (Component src, int type, long when, int modifier,
int x, int y)
Here,
• src is a reference to the object that generated this event.
• The type of the event is specified by type.
• The system time at which the mouse event occurred is passed
in when.
• The modifier argument specifies which modifiers were
pressed when this mouse event occurred.
• The coordinates of the mouse are passed in x and y. The click
count is passed in clicks.
MouseEvent class Methods :
1. int getX()
2. int getY()
The getX() and getY() methods returns the x and y coordinates of
the mouse within the component when the event occurred.
public void mouseClicked(MouseEvent e)
{ x = e.getX();
y = e.getY();
System.out.println("X:" + x + " " + "Y:" + y); }
3. Int getClickCount()
it returns number of mouse clicks.
5. TextEvent Class :
• The TextEvent is generated when character is entered in
the text fields or text area
TextEvent has the constructor :
TextEvent (Object src, int type)
Here,
• src is a reference to the object that generated this event.
• The type of the event is specified by type.
TextEvent class Methods :
1. String paramString()
It returns a parameter string identifying this text event.
Fields:
• Text_VALUE_CHANGED :
This event id indicates that objects text changed.
public void textValueChanged(TextEvent e)
{
t2.setText(t1.getText());
}
Advance java programming- Event handling
6. WindowEvent Class.
This is an event that indicates that a window has
changed its state.
WindowEvent class defines the following integer constants
that can be used to identify them:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_ DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified. (Maximized)
WINDOW_ICONIFIED The window was iconified. (Minimized)
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window ch
WindowEvent class is a subclass of
ComponentEvent. It uses the constructor:
1. WindowEvent (Window src)
2. WindowEvent (Window src, int type,)
Here,
• src is a reference to the object that generated this
event.
• The type of the event is specified by type.
Fields of WindowEvent Class :
1. Window getOppositeWindow()
Returns the other window involved in this focus or activation
change.
2. int getNewState()
It returns the new state of the window.
3. int getOldState()
It returns the previous state of the window.
4. Window getWindow()
The getWindow() method returns the object that generated the
event.
3.3. Adapter classes.
• An adapter class provides the default implementation of all
methods in an event listener interface.
• Adapter classes are very useful when you want to process
only few of the events that are handled by a particular event
listener interface.
• You can define a new class by extending one of the adapter
classes and implement only those events relevant to you.
• Adapter class is basically a class in java that implements an
interface with a set of dummy methods.
• The famous adapter classes in Java API are WindowAdapter,
ComponentAdapter, ContainerAdapter, FocusAdapter,
KeyAdapter, MouseAdapter, and MouseMotionAdapter.
• Eg. WindowAdapter class implements WindowListener
interface and make seven empty implementation.
• The adapter classes are found in java.awt.event, java.awt.dnd
and javax.swing.event packages.
java.awt.event Adapter classes :
Below are some of the Adapter classes and their
corresponding listener interface. These are present in the
Abstract Window Toolkit of the Java package.
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
1. ContainerAdapter class :
The interface ContainerListener is used for receiving
container events. The class that process container events
needs to implements this interface.
• Class declaration :
Following is the declaration for
java.awt.event.ContainerListener interface:
public interface ContainerListener
extends EventListener
Methods of ContainerAdapter Class :
1. void componentAdded(ContainerEvent e)
Invoked when a component has been added to
the container.
2. void componentRemoved(ContainerEvent e)
Invoked when a component has been removed
from the container.
2. KeyAdapter class :
The class KeyAdapter is an abstract (adapter) class for
receiving keyboard events. All methods of this class are empty.
This class is convenience class for creating listener objects.
• Class declaration of KeyAdapter :
Following is the declaration for java.awt.event.KeyAdapter
class:
public abstract class KeyAdapter
extends Object
implements KeyListener
• Methods of KeyAdapter Class :
1. void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
2. void keyReleased(KeyEvent e)
Invoked when a key has been released.
3. void keyTyped(KeyEvent e)
Invoked when a key has been typed.
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter
{
TextArea area;
Frame f;
KeyAdapterExample()
{
f = new Frame ("Key Adapter");
area = new TextArea();
area.setBounds (20, 80, 300, 300);
// adding KeyListener to text area
area.addKeyListener(this);
f.add(l);
f.add(area);
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
public void keyReleased (KeyEvent e)
{
String text = area.getText();
System.out.println(text);}
public static void main(String[] args)
{
new KeyAdapterExample();
}
}
3. FocusAdapter class :
The class FocusAdapter is an abstract (adapter) class for
receiving keyboard focus events. All methods of this class are
empty. This class is convenience class for creating listener
objects.
• Class declaration of FocusAdapter :
Following is the declaration for java.awt.event.FocusAdapter
class:
public abstract class FocusAdapter
extends Object
implements FocusListener
• Methods of FocusAdapter Class :
1. void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2. focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.
4. WindowAdapter class :
The class WindowAdapter is an abstract (adapter) class for
receiving window events. All methods of this class are empty.
This class is convenience class for creating listener objects.
• Class declaration of WindowAdapter :
Following is the declaration for java.awt.event.WindowAdapter
class:
public abstract class WindowAdapter
extends Object
implements WindowListener, WindowStateListener,
WindowFocusListener
• Methods of WindowAdapter Class :
1. void windowActivated(WindowEvent e)
Invoked when a window is activated.
2. void windowClosed(WindowEvent e)
Invoked when a window has been closed.
3. void windowClosing(WindowEvent e)
Invoked when a window is in the process of being
closed.
4. void windowDeactivated(WindowEvent e)
Invoked when a window is de-activated.
5. void windowDeiconified(WindowEvent e)
Invoked when a window is de-iconified.
6. void windowIconified(WindowEvent e)
Invoked when a window is iconified.
7. void windowOpened(WindowEvent e)
Invoked when a window has been opened.
8 void windowStateChanged(WindowEvent e)
Invoked when a window state is changed.
5. MouseAdapter class :
The class MouseAdapter is an abstract (adapter) class for
receiving mouse events. All methods of this class are empty.
This class is convenience class for creating listener objects.
• Class declaration of MouseAdapter :
Following is the declaration for java.awt.event.MouseAdapter
class:
public abstract class MouseAdapter
extends Object
implements MouseListener, MouseWheelListener,
MouseMotionListener
• Class constructors of MouseAdapter :
1. MouseAdapter()
• Methods of MouseAdapter Class :
1. void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed
and released) on a component.
2. void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and
then dragged.
3. void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
4. void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
5. void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a
component but no buttons have been pushed.
6. void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
7. void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
8. void mouseWheelMoved(MouseWheelEvent e)
Invoked when the mouse wheel is rotated.
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{
Frame f;
MouseAdapterExample()
{
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
public void mouseClicked (MouseEvent e)
{
// creating the Graphics object and fetching them from the Frame object
using getGraphics() method
Graphics g = f.getGraphics();
g.setColor (Color.BLUE);
g.fillOval (e.getX(), e.getY(), 30, 30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
6. ComponentAdapter class :
An abstract adapter class is used for receiving component
events. The methods in this class are empty. This class exists as
convenience for creating listener objects.
• Class declaration of MouseAdapter :
Following is the declaration for java.awt.event, ComponentAdapter
class:
public abstract class ComponentAdapter
extends Object
implements ComponentListener
• Constructors os ComponentAdapter Class :
Public componentAdapter()
• Methods of ComponentAdapter Class :
1. void componentResized(ComponentEvent e)
Invoked when the components size changes.
2. void componentMoved(ComponentEvent e)
Invoked when the components position changes.
3. void componentShown(ComponentEvent e)
Invoked when the component has been made visible.
4. void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.
7. MouseMotionAdapter class :
The class MouseMotionAdapter is an abstract (adapter) class
for receiving mouse motion events. All methods of this class are
empty. This class is convenience class for creating listener
objects.
• Class declaration of MouseMotionAdapter :
Following is the declaration for
java.awt.event.MouseMotionAdapter class:
public abstract class MouseMotionAdapter
extends Object
implements MouseMotionListener
• Class constructors of MouseMotionAdapter :
1. MouseMotionAdapter()
• Methods of MouseMotionAdapter Class :
1. void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a
component and then dragged.
2. void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto
a component but no buttons have been pushed.
3.5. Event Listener Interfaces :
ActionListener interface
ItemListener interface
MouseListener interface
MouseMotionListener interface
KeyListener interface
TextListener interface
WindowListener interface
3.5 Event Listener Interfaces :
• The Event listener represent the interfaces
responsible to handle events.
• Java provides us various Event listener classes
but we will discuss those which are more
frequently used.
• Every method of an event listener method has
a single argument as an object which is
subclass of EventObject class.
No. Event Listener interfaces Description
1 ActionListener interface This interface is used for receiving the action events.
2 ItemListener interface This interface is used for receiving the item events.
3 MouseListener interface This interface is used for receiving the mouse events.
4 MouseMotionListener
Interface
This interface is used for receiving the mouse motion
events.
5 KeyListener interface This interface is used for receiving the key events.
6 TextListener interface This interface is used for receiving the text events.
7 WindowListener
interface
This interface is used for receiving the window
events.
1. ActionListener interface :
• The Java ActionListener is notified whenever you click on the
button or menu item. It is notified against ActionEvent.
• The ActionListener interface is found in java.awt.event package.
• This interface defines only one method: actionPerformed().
• The actionPerformed() is invoked when an action event occurs.
• This method is defined as :
void actionPerformed(ActionEvent ae)
The actionPerformed() method is invoked automatically whenever
you click on the registered component.
If you implement the ActionListener class, you need to follow 3
steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListe
ner
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this); //passing current instance
//add components and set size, layout and visibility
add(b); add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
} }
2. ItemListener interface :
• The Java ItemListener is notified whenever you click on the
checkbox. It is notified against ItemEvent.
• The ItemListener interface is found in java.awt.event package.
• This interface defines only one method: itemStateChanged().
• The itemStateChanged() is invoked when the state of an item
changes.
• Its general form is shown below :
void itemStateChanged(ItemEvent ie)
The itemStateChanged() method is invoked automatically whenever
you click or unclick on the registered checkbox component.
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener
{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample()
{
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
3. MouseListener interface :
• The Java MouseListener is notified whenever you
change the state of mouse.
• The MouseListener interface is found in java.awt.event
package.
• This interface defines five methods.
1. void mouseClicked(MouseEvent e)
2. void mouseEntered(MouseEvent e)
3. void mouseExited(MouseEvent e)
4. void mousePressed(MouseEvent e)
5. void mouseReleased(MouseEvent e)
• If the mouse is pressed and released at the
same point, mouseClicked() is invoked.
• When the mouse enters a coponent, the
mouseEntered() method called.
• When it leaves, mouseExited() is called.
• The mousePressed() and mouseReleased()
method are invoked when the mouse is pressed
and released,respectively
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener
{
Label l;
MouseListenerExample()
{ addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{ l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{ l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{ l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{ l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{ l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
4. MouseMotionListener interface :
• The Java MouseMotionListener is notified whenever
you move or drag mouse. It is notified against MouseEvent.
• The MouseMotionListener interface is found in
java.awt.event package.
• This interface defines two methods.
1. void mouseDragged(MouseEvent e)
2. void mouseMoved(MouseEvent e)
• The mouseDragged() method is called multiple times as the mouse
is dragged.
• The mouseMove() method is called multiple times as the mouse is
moved.
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends
Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),10,10);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
5. KeyListener interface :
• The Java KeyListener is notified whenever you change the
state of key. It is notified against KeyEvent.
• The KeyListener interface is found in java.awt.event package.
• This interface defines three methods.
1. void keyPressed(KeyEvent e)
2. void keyReleased(KeyEvent e)
3. void keyTyped(KeyEvent e)
• The keyPressed() and keyReleased() methods are invoked
when a key is pressed and released, respectively.
• The keyTyped() method is invoked when a character has been
changed.
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public void keyPressed (KeyEvent e)
{ l.setText ("Key Pressed");
System.out.println("Key Pressed.....");
}
public void keyReleased (KeyEvent e)
{
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e)
{
l.setText ("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
6. TextListener interface :
• The TextListener interface is found in java.awt.event
package.
• This method is defined as :
void textValueChanged(TextEvent te)
import java.awt.*;
import java.awt.event.*;
public class TextListenerExample extends Frame implements TextListener
{
TextField t1,t2;
public TextListenerExample()
{
setLayout(new FlowLayout());
t1 = new TextField(50);
t2 = new TextField(50);
add(t1);
add(t2);
t2.setEditable(false);
t1.addTextListener(this);
}
public void textValueChanged(TextEvent e)
{
t2.setText(t1.getText());
}
public static void main(String[] args)
{
TextListenerExample tl= new TextListenerExample();
tl.setTitle("Text Event....");
tl.setSize(300,300);
tl.setLayout(null);
tl.setVisible(true);
}
}
7. WindowListener interface :
• The Java WindowListener is notified whenever you change
the state of window. It is notified against WindowEvent.
• The WindowListener interface is found in java.awt.event
package.
• Methods of WindowListener interface are given below:
1. windowActivated(WindowEvent e);
2. windowClosed(WindowEvent e);
3. windowClosing(WindowEvent e);
4. windowDeactivated(WindowEvent e);
5. windowDeiconified(WindowEvent e);
6. windowIconified(WindowEvent e);
7. windowOpened(WindowEvent e);
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener {
WindowExample() {
// adding WindowListener to the frame
addWindowListener(this);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public static void main(String[] args) {
new WindowExample();
}
public void windowActivated (WindowEvent arg0) {
System.out.println("activated");
}
public void windowClosed (WindowEvent arg0) {
System.out.println("closed");
}
public void windowClosing (WindowEvent arg0) {
System.out.println("closing");
dispose();
}
public void windowDeactivated (WindowEvent arg0) {
System.out.println("deactivated");
}
public void windowDeiconified (WindowEvent arg0) {
System.out.println("deiconified");
}
public void windowIconified(WindowEvent arg0) {
System.out.println("iconified");
}
public void windowOpened(WindowEvent arg0) {
System.out.println("opened");
}
}
• The windowActivated() and windowDeactivated() methods
are invoked when a window is activated or deactivated,
respectively.
• If a window is iconified, the windowIconified() method is
called.
• When a window is deiconified, the windowDeiconified()
method is called.
• When a window is opened or closed, the windowOpened()
or windowClosed() methods are called, respectively.
• The windowClosing() method is called when a window is
being closed.
3.4. Inner classes :
Inner classes are the nested classes. That means these are
the classes that are defined inside the other classes.
Syntax,
Access_modifier class OuterClass
{
//code
Access_modifier class InnerClass
{
//code
}
}
Properties of Inner classes :
• The outer class can inherit as many number of inner class objects as it
wants.
• If the outer class and the curresponding inner class both are public than
any other class can create an instance of this inner class.
• The inner class objects do not get instantiated with an outer class
object.
• The outer class can call the private methods of inner class.
• Inner class mode has free access to all elements of the outer class
object that contains it.
• If the inner class has a variable with same name then the outer class’s
variable can be accessed like this :
outerclassname.this.variable_name
Types of Inner classes :
There are four types of inner classes :
1. Static Member Classes
2. Member Classes
3. Local Classes
4. Anonymous Classes
Thank you

More Related Content

PPT
Unit 6 Java
PPTX
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
PPTX
Event Handling in JAVA
PDF
Ajp notes-chapter-03
PDF
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
PPTX
Event Handling in Java
PPTX
tL20 event handling
PPTX
AJP Event classes.pptx
Unit 6 Java
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
Event Handling in JAVA
Ajp notes-chapter-03
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Event Handling in Java
tL20 event handling
AJP Event classes.pptx

Similar to Advance java programming- Event handling (20)

PDF
Java Programming :Event Handling(Types of Events)
PPTX
Module3.11.pptx
PPTX
UNIT III Event Handling of the car j.pptx
PPTX
Module 5.pptx
PPT
Java gui event
PPT
Events1
DOCX
Dr Jammi Ashok - Introduction to Java Material (OOPs)
PPT
unit-6.pptbjjdjdkd ndmdkjdjdjjdkfjjfjfjfj
PPTX
Event handling
PPTX
Advance Java Programming(CM5I) Event handling
PDF
Unit-3 event handling
PPTX
event-handling.pptx
PPTX
What is Event
PPTX
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
PDF
Event Handling in Java as per university
PPTX
EVENT HANDLING in Object Oriented Programming in Java
PPT
Chapter 8 event Handling.ppt m m m m m m
PPTX
Java event processing model in c# and java
PPTX
Event handling in Java(part 1)
Java Programming :Event Handling(Types of Events)
Module3.11.pptx
UNIT III Event Handling of the car j.pptx
Module 5.pptx
Java gui event
Events1
Dr Jammi Ashok - Introduction to Java Material (OOPs)
unit-6.pptbjjdjdkd ndmdkjdjdjjdkfjjfjfjfj
Event handling
Advance Java Programming(CM5I) Event handling
Unit-3 event handling
event-handling.pptx
What is Event
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
Event Handling in Java as per university
EVENT HANDLING in Object Oriented Programming in Java
Chapter 8 event Handling.ppt m m m m m m
Java event processing model in c# and java
Event handling in Java(part 1)
Ad

Recently uploaded (20)

PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
composite construction of structures.pdf
PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
anatomy of limbus and anterior chamber .pptx
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
PDF
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
Structs to JSON How Go Powers REST APIs.pdf
composite construction of structures.pdf
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
CH1 Production IntroductoryConcepts.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Chapter 6 Design in software Engineeing.ppt
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
anatomy of limbus and anterior chamber .pptx
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Arduino robotics embedded978-1-4302-3184-4.pdf
573137875-Attendance-Management-System-original
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
Ad

Advance java programming- Event handling

  • 1. SHARAD INSTITUTE OF TECHNOLOGY COLLEGE OF ENGINEERING ,YADRAV ADVANCED JAVA PROGRAMMING UNIT : 3 Event Handling Presented By : Mr. PRASHANT B.PATIL DEPARTMENT OF COMPUTER & SCIENCE ENGINEERING
  • 2. 3. Event Handling 3.1. The delegation Event Model : Event sources, Event Listeners. 3.2. Event classes : the ActionEvent class, the ItemEvent class, the KeyEvent class, the MouseEvent class, the TextEvent class, the WindowEvent class. 3.3. Adapter classes. 3.4. Inner classes. 3.5. Event Listener Interfaces : Action Listener interface, ItemListener interface, KeyListener interface, MouseListener interface, TextListener interface, WindowListener interface.
  • 3. What is an Event? Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.
  • 4. Types of Event : The events can be broadly classified into two categories: 1. Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc. 2. Background Events - Events that don’t require interactions of users to generate an event are known as background events. Examples of these events are operating system failures/interrupts, operation completion, etc
  • 5. Introduction to Event Handling : Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
  • 6. 3.1. The delegation Event Model : The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple, a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an event is received, the listener processes the event and then returns.
  • 7. In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the original Java 1.0 approach.
  • 8. In the delegation event model, The event model is based on the Event Source and Event Listeners. Event Source is any object which creates the message / event. The Event Listener is an object that receives the messages / events.
  • 10. 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. Here is the general form: public void addTypeListener (TypeListener el ) Here, Type is the name of the event, and el is a reference to the event listener.
  • 11. 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. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.
  • 12. Some sources may allow only one listener to register. The general form of such a method is this: public void addTypeListener(TypeListener el ) throws java.util.TooManyListenersException Here, Type is the name of the event, and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event.
  • 13. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el ) Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners.
  • 14. • 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 methods that receive and process events are defined in a set of interfaces, such as those found in java.awt.event. For example, ActionListener, ItemListener, KeyListener MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved.
  • 15. 3.2. Event classes : • Event classes are the responsible for handling events in the event handling mechanism. • All the listeners and its methods are also encapsulated with event classes. • All the event classes are present under java.awt.event package. • EventObject class it is the root class from which all event state objects shall be derived. • It is the superclass of all events.
  • 16. • All events are constructed with a reference to the object. • The EventObject class is at the top/root of the Java event class hierarchy. EventObject class constructor is: EventObject (Object src) • Here, src is the objects that generates the event.
  • 17. EventObject class Methods : The getSource() and toString() are the methods of the EventObject class. 1. getSource( ) The getSource( ) method returns the source of the event. • Its general form is shown here: Object getSource( ) The getSource method is used in the actionPerformed method to determine which button was clicked. 2. toString( ) toString( ) returns the string equivalent of the event. The toString() method returns the String representation of the object. If you want to represent any object as a string If you print any object, Java compiler internally invokes the toString() method on the object.
  • 18. • There is getID( ) method belonging to java.awt.event package returns the nature of the event. Or can be used to determine the type of the event. • Syntax is, int getID( ) • getId() method returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused
  • 19. Event classes : 1. ActionEvent Class. 2. ItemEvent Class. 3. KeyEvent Class. 4. MouseEvent Class. 5. TextEvent Class. 6. WindowEvent Class.
  • 20. 1. ActionEvent Class : An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component. An instance of the ActionEvent class is passed to the ActionListener when an action event occurs. You can use this object to determine information about the event. actionPerformed() method The actionPerformed() method is invoked automatically whenever you click on the registered component.
  • 21. ActionEvent constructor : ActionEvent (Object src) 1. Register the component with the Listener: component.addActionListener(instanceOfListenerclass); 2. Override the actionPerformed() method: public void actionPerformed(ActionEvent e) { //Write the code here }
  • 22. ActionEvent Methods: 1. String getActionCommand() : This method is useful for obtaining the Command string which is specified during the generation of event. Returns the object on which the event occurred. 2. int getWhen() : The getWhen() method returns the time at which the event occurs.
  • 24. There are two types of item events which are identified by two integer constants : ItemEvent defiens one integer constant, ITEM_STATE_CHANGED that signifies a change of state. DESELECTED The user deselected an item. SELECTED The user selected an item.
  • 25. ItemEvent Methods : 1. The getItem() : returns a reference to the item that generated an event. 2. ItemSelectable getItemSelectable() : The getItemSelectable() method returns a reference to the ItemSelectable object that generated an event. 3. Int getStateChange() : The getStateChange() method returns the state change(i.e, SELECTED or DESELECTED) for an event.
  • 27. 3. KeyEvent Class : • This event is generated when key on the keyboard is pressed or released. • There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. • The first two events are generated when a key is pressed or released. • The last event occurs when a character is generated.
  • 28. Many other integer constants that are defined by The VK constants specifies virtual key codes. For example, pressing the Shift key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event will be fired with VK_A. Separately, a KEY_TYPED event with a keyChar value of 'A' is generated VK_ALT VK_DOWN VK_LEFT VK_RIGHT VK_CANCLE VK_ENTER VK_ PAGE_DOWN VK_SHIFT VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP
  • 29. Constructor of Keyevent Class : 1. KeyEvent (Component src) Here, • src is a reference to the object that generated this event. • KeyEvent is a subclass of InputEvent
  • 30. KeyEvent Methods : 1. char getKeyChar () The getKeyChar() method returns the character that was entered. public void keyTyped(KeyEvent ke) { char keyChar = ke.getKeyChar(); if (keyChar == 'a') { System.out.println("You typed 'a'"); }
  • 31. 2. int getKeyCode () getKeyCode() method returns the key code. public void keyPressed(KeyEvent ke) { int keyCode = ke.getKeyCode(); if (keyCode == 66) { System.out.println("You Typed b"); } }
  • 32. // adding the KeyListener to the text area obj.addKeyListener(this); • public void keyPressed (KeyEvent e) { l.setText ("Key Pressed"); } • public void keyReleased (KeyEvent e) { l.setText ("Key Released"); } • public void keyTyped (KeyEvent e) { l.setText ("Key Typed"); }
  • 33. 4. MouseEvent Class : This event occurs when mouse action occurs on a component. It reacts for both mouse event and mouse motion event. Mouse Events : A mouse button is pressed A mouse button is released A mouse button is clicked (pressed or released) The mouse cursor enters a component The mouse cursor exits a component Mouse Motion Events : The mouse is moved The mouse is dragged
  • 34. There are seven types of mouse events. MouseEvent class defines the following integer constants: MOUSE_CLICKED The user clicked the mouse. MOUSE_DRAGGED The user dragged the mouse. MOUSE_ENTERED The mouse entered a component. MOUSE_EXITED The mouse exited from a component. MOUSE_MOVED The mouse moved. MOUSE_PRESSED The mouse was pressed. MOUSE_RELEASED The mouse was released.
  • 35. MouseEvent class is a subclass of InputEvent. It uses the constructor: MouseEvent (Component src, int type, long when, int modifier, int x, int y) Here, • src is a reference to the object that generated this event. • The type of the event is specified by type. • The system time at which the mouse event occurred is passed in when. • The modifier argument specifies which modifiers were pressed when this mouse event occurred. • The coordinates of the mouse are passed in x and y. The click count is passed in clicks.
  • 36. MouseEvent class Methods : 1. int getX() 2. int getY() The getX() and getY() methods returns the x and y coordinates of the mouse within the component when the event occurred. public void mouseClicked(MouseEvent e) { x = e.getX(); y = e.getY(); System.out.println("X:" + x + " " + "Y:" + y); } 3. Int getClickCount() it returns number of mouse clicks.
  • 37. 5. TextEvent Class : • The TextEvent is generated when character is entered in the text fields or text area TextEvent has the constructor : TextEvent (Object src, int type) Here, • src is a reference to the object that generated this event. • The type of the event is specified by type.
  • 38. TextEvent class Methods : 1. String paramString() It returns a parameter string identifying this text event. Fields: • Text_VALUE_CHANGED : This event id indicates that objects text changed. public void textValueChanged(TextEvent e) { t2.setText(t1.getText()); }
  • 40. 6. WindowEvent Class. This is an event that indicates that a window has changed its state. WindowEvent class defines the following integer constants that can be used to identify them: WINDOW_ACTIVATED The window was activated. WINDOW_CLOSED The window has been closed. WINDOW_CLOSING The user requested that the window be closed. WINDOW_ DEACTIVATED The window was deactivated. WINDOW_DEICONIFIED The window was deiconified. (Maximized) WINDOW_ICONIFIED The window was iconified. (Minimized) WINDOW_OPENED The window was opened. WINDOW_STATE_CHANGED The state of the window ch
  • 41. WindowEvent class is a subclass of ComponentEvent. It uses the constructor: 1. WindowEvent (Window src) 2. WindowEvent (Window src, int type,) Here, • src is a reference to the object that generated this event. • The type of the event is specified by type.
  • 42. Fields of WindowEvent Class : 1. Window getOppositeWindow() Returns the other window involved in this focus or activation change. 2. int getNewState() It returns the new state of the window. 3. int getOldState() It returns the previous state of the window. 4. Window getWindow() The getWindow() method returns the object that generated the event.
  • 43. 3.3. Adapter classes. • An adapter class provides the default implementation of all methods in an event listener interface. • Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. • You can define a new class by extending one of the adapter classes and implement only those events relevant to you. • Adapter class is basically a class in java that implements an interface with a set of dummy methods.
  • 44. • The famous adapter classes in Java API are WindowAdapter, ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter, and MouseMotionAdapter. • Eg. WindowAdapter class implements WindowListener interface and make seven empty implementation. • The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
  • 45. java.awt.event Adapter classes : Below are some of the Adapter classes and their corresponding listener interface. These are present in the Abstract Window Toolkit of the Java package. Adapter class Listener interface WindowAdapter WindowListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener FocusAdapter FocusListener ComponentAdapter ComponentListener ContainerAdapter ContainerListener
  • 46. 1. ContainerAdapter class : The interface ContainerListener is used for receiving container events. The class that process container events needs to implements this interface. • Class declaration : Following is the declaration for java.awt.event.ContainerListener interface: public interface ContainerListener extends EventListener
  • 47. Methods of ContainerAdapter Class : 1. void componentAdded(ContainerEvent e) Invoked when a component has been added to the container. 2. void componentRemoved(ContainerEvent e) Invoked when a component has been removed from the container.
  • 48. 2. KeyAdapter class : The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects. • Class declaration of KeyAdapter : Following is the declaration for java.awt.event.KeyAdapter class: public abstract class KeyAdapter extends Object implements KeyListener
  • 49. • Methods of KeyAdapter Class : 1. void keyPressed(KeyEvent e) Invoked when a key has been pressed. 2. void keyReleased(KeyEvent e) Invoked when a key has been released. 3. void keyTyped(KeyEvent e) Invoked when a key has been typed.
  • 50. import java.awt.*; import java.awt.event.*; public class KeyAdapterExample extends KeyAdapter { TextArea area; Frame f; KeyAdapterExample() { f = new Frame ("Key Adapter"); area = new TextArea(); area.setBounds (20, 80, 300, 300);
  • 51. // adding KeyListener to text area area.addKeyListener(this); f.add(l); f.add(area); f.setSize (400, 400); f.setLayout (null); f.setVisible (true); } public void keyReleased (KeyEvent e) { String text = area.getText(); System.out.println(text);} public static void main(String[] args) { new KeyAdapterExample(); } }
  • 52. 3. FocusAdapter class : The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects. • Class declaration of FocusAdapter : Following is the declaration for java.awt.event.FocusAdapter class: public abstract class FocusAdapter extends Object implements FocusListener
  • 53. • Methods of FocusAdapter Class : 1. void focusGained(FocusEvent e) Invoked when a component gains the keyboard focus. 2. focusLost(FocusEvent e) Invoked when a component loses the keyboard focus.
  • 54. 4. WindowAdapter class : The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects. • Class declaration of WindowAdapter : Following is the declaration for java.awt.event.WindowAdapter class: public abstract class WindowAdapter extends Object implements WindowListener, WindowStateListener, WindowFocusListener
  • 55. • Methods of WindowAdapter Class : 1. void windowActivated(WindowEvent e) Invoked when a window is activated. 2. void windowClosed(WindowEvent e) Invoked when a window has been closed. 3. void windowClosing(WindowEvent e) Invoked when a window is in the process of being closed.
  • 56. 4. void windowDeactivated(WindowEvent e) Invoked when a window is de-activated. 5. void windowDeiconified(WindowEvent e) Invoked when a window is de-iconified. 6. void windowIconified(WindowEvent e) Invoked when a window is iconified.
  • 57. 7. void windowOpened(WindowEvent e) Invoked when a window has been opened. 8 void windowStateChanged(WindowEvent e) Invoked when a window state is changed.
  • 58. 5. MouseAdapter class : The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects. • Class declaration of MouseAdapter : Following is the declaration for java.awt.event.MouseAdapter class: public abstract class MouseAdapter extends Object implements MouseListener, MouseWheelListener, MouseMotionListener
  • 59. • Class constructors of MouseAdapter : 1. MouseAdapter() • Methods of MouseAdapter Class : 1. void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released) on a component. 2. void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. 3. void mouseEntered(MouseEvent e) Invoked when the mouse enters a component.
  • 60. 4. void mouseExited(MouseEvent e) Invoked when the mouse exits a component. 5. void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. 6. void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. 7. void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. 8. void mouseWheelMoved(MouseWheelEvent e) Invoked when the mouse wheel is rotated.
  • 61. import java.awt.*; import java.awt.event.*; public class MouseAdapterExample extends MouseAdapter { Frame f; MouseAdapterExample() { f = new Frame ("Mouse Adapter"); // adding MouseListener to the Frame f.addMouseListener(this); f.setSize (300, 300); f.setLayout (null); f.setVisible (true); }
  • 62. public void mouseClicked (MouseEvent e) { // creating the Graphics object and fetching them from the Frame object using getGraphics() method Graphics g = f.getGraphics(); g.setColor (Color.BLUE); g.fillOval (e.getX(), e.getY(), 30, 30); } public static void main(String[] args) { new MouseAdapterExample(); } }
  • 63. 6. ComponentAdapter class : An abstract adapter class is used for receiving component events. The methods in this class are empty. This class exists as convenience for creating listener objects. • Class declaration of MouseAdapter : Following is the declaration for java.awt.event, ComponentAdapter class: public abstract class ComponentAdapter extends Object implements ComponentListener • Constructors os ComponentAdapter Class : Public componentAdapter()
  • 64. • Methods of ComponentAdapter Class : 1. void componentResized(ComponentEvent e) Invoked when the components size changes. 2. void componentMoved(ComponentEvent e) Invoked when the components position changes. 3. void componentShown(ComponentEvent e) Invoked when the component has been made visible. 4. void componentHidden(ComponentEvent e) Invoked when the component has been made invisible.
  • 65. 7. MouseMotionAdapter class : The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects. • Class declaration of MouseMotionAdapter : Following is the declaration for java.awt.event.MouseMotionAdapter class: public abstract class MouseMotionAdapter extends Object implements MouseMotionListener
  • 66. • Class constructors of MouseMotionAdapter : 1. MouseMotionAdapter() • Methods of MouseMotionAdapter Class : 1. void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. 2. void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
  • 67. 3.5. Event Listener Interfaces : ActionListener interface ItemListener interface MouseListener interface MouseMotionListener interface KeyListener interface TextListener interface WindowListener interface
  • 68. 3.5 Event Listener Interfaces : • The Event listener represent the interfaces responsible to handle events. • Java provides us various Event listener classes but we will discuss those which are more frequently used. • Every method of an event listener method has a single argument as an object which is subclass of EventObject class.
  • 69. No. Event Listener interfaces Description 1 ActionListener interface This interface is used for receiving the action events. 2 ItemListener interface This interface is used for receiving the item events. 3 MouseListener interface This interface is used for receiving the mouse events. 4 MouseMotionListener Interface This interface is used for receiving the mouse motion events. 5 KeyListener interface This interface is used for receiving the key events. 6 TextListener interface This interface is used for receiving the text events. 7 WindowListener interface This interface is used for receiving the window events.
  • 70. 1. ActionListener interface : • The Java ActionListener is notified whenever you click on the button or menu item. It is notified against ActionEvent. • The ActionListener interface is found in java.awt.event package. • This interface defines only one method: actionPerformed(). • The actionPerformed() is invoked when an action event occurs. • This method is defined as : void actionPerformed(ActionEvent ae) The actionPerformed() method is invoked automatically whenever you click on the registered component.
  • 71. If you implement the ActionListener class, you need to follow 3 steps: 1) Implement the ActionListener interface in the class: public class ActionListenerExample Implements ActionListe ner 2) Register the component with the Listener: component.addActionListener(instanceOfListenerclass); 3) Override the actionPerformed() method: public void actionPerformed(ActionEvent e){ //Write the code here }
  • 72. import java.awt.*; import java.awt.event.*; class AEvent extends Frame implements ActionListener { TextField tf; AEvent() { //create components tf=new TextField(); tf.setBounds(60,50,170,20); Button b=new Button("click me"); b.setBounds(100,120,80,30);
  • 73. //register listener b.addActionListener(this); //passing current instance //add components and set size, layout and visibility add(b); add(tf); setSize(300,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { tf.setText("Welcome"); } public static void main(String args[]){ new AEvent(); } }
  • 74. 2. ItemListener interface : • The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. • The ItemListener interface is found in java.awt.event package. • This interface defines only one method: itemStateChanged(). • The itemStateChanged() is invoked when the state of an item changes. • Its general form is shown below : void itemStateChanged(ItemEvent ie) The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox component.
  • 75. import java.awt.*; import java.awt.event.*; public class ItemListenerExample implements ItemListener { Checkbox checkBox1,checkBox2; Label label; ItemListenerExample() { Frame f= new Frame("CheckBox Example"); label = new Label(); label.setAlignment(Label.CENTER); label.setSize(400,100);
  • 76. checkBox1 = new Checkbox("C++"); checkBox1.setBounds(100,100, 50,50); checkBox2 = new Checkbox("Java"); checkBox2.setBounds(100,150, 50,50); f.add(checkBox1); f.add(checkBox2); f.add(label); checkBox1.addItemListener(this); checkBox2.addItemListener(this); f.setSize(400,400); f.setLayout(null); f.setVisible(true); }
  • 77. public void itemStateChanged(ItemEvent e) { if(e.getSource()==checkBox1) label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); if(e.getSource()==checkBox2) label.setText("Java Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } public static void main(String args[]) { new ItemListenerExample(); } }
  • 78. 3. MouseListener interface : • The Java MouseListener is notified whenever you change the state of mouse. • The MouseListener interface is found in java.awt.event package. • This interface defines five methods. 1. void mouseClicked(MouseEvent e) 2. void mouseEntered(MouseEvent e) 3. void mouseExited(MouseEvent e) 4. void mousePressed(MouseEvent e) 5. void mouseReleased(MouseEvent e)
  • 79. • If the mouse is pressed and released at the same point, mouseClicked() is invoked. • When the mouse enters a coponent, the mouseEntered() method called. • When it leaves, mouseExited() is called. • The mousePressed() and mouseReleased() method are invoked when the mouse is pressed and released,respectively
  • 80. import java.awt.*; import java.awt.event.*; public class MouseListenerExample extends Frame implements MouseListener { Label l; MouseListenerExample() { addMouseListener(this); l=new Label(); l.setBounds(20,50,100,20); add(l); setSize(300,300); setLayout(null); setVisible(true); }
  • 81. public void mouseClicked(MouseEvent e) { l.setText("Mouse Clicked"); } public void mouseEntered(MouseEvent e) { l.setText("Mouse Entered"); } public void mouseExited(MouseEvent e) { l.setText("Mouse Exited"); } public void mousePressed(MouseEvent e) { l.setText("Mouse Pressed"); } public void mouseReleased(MouseEvent e) { l.setText("Mouse Released"); } public static void main(String[] args) { new MouseListenerExample(); }
  • 82. 4. MouseMotionListener interface : • The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. • The MouseMotionListener interface is found in java.awt.event package. • This interface defines two methods. 1. void mouseDragged(MouseEvent e) 2. void mouseMoved(MouseEvent e) • The mouseDragged() method is called multiple times as the mouse is dragged. • The mouseMove() method is called multiple times as the mouse is moved.
  • 83. import java.awt.*; import java.awt.event.*; public class MouseMotionListenerExample extends Frame implements MouseMotionListener{ MouseMotionListenerExample(){ addMouseMotionListener(this); setSize(300,300); setLayout(null); setVisible(true); }
  • 84. public void mouseDragged(MouseEvent e) { Graphics g=getGraphics(); g.setColor(Color.BLUE); g.fillOval(e.getX(),e.getY(),10,10); } public void mouseMoved(MouseEvent e) {} public static void main(String[] args) { new MouseMotionListenerExample(); } }
  • 85. 5. KeyListener interface : • The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. • The KeyListener interface is found in java.awt.event package. • This interface defines three methods. 1. void keyPressed(KeyEvent e) 2. void keyReleased(KeyEvent e) 3. void keyTyped(KeyEvent e) • The keyPressed() and keyReleased() methods are invoked when a key is pressed and released, respectively. • The keyTyped() method is invoked when a character has been changed.
  • 86. import java.awt.*; import java.awt.event.*; public class KeyListenerExample extends Frame implements KeyListener { Label l; TextArea area; KeyListenerExample() { l = new Label(); l.setBounds (20, 50, 100, 20); area = new TextArea(); area.setBounds (20, 80, 300, 300); area.addKeyListener(this); add(l); add(area); setSize (400, 400); setLayout (null); setVisible (true); }
  • 87. public void keyPressed (KeyEvent e) { l.setText ("Key Pressed"); System.out.println("Key Pressed....."); } public void keyReleased (KeyEvent e) { l.setText ("Key Released"); } public void keyTyped (KeyEvent e) { l.setText ("Key Typed"); } public static void main(String[] args) { new KeyListenerExample(); } }
  • 88. 6. TextListener interface : • The TextListener interface is found in java.awt.event package. • This method is defined as : void textValueChanged(TextEvent te)
  • 89. import java.awt.*; import java.awt.event.*; public class TextListenerExample extends Frame implements TextListener { TextField t1,t2; public TextListenerExample() { setLayout(new FlowLayout()); t1 = new TextField(50); t2 = new TextField(50); add(t1); add(t2); t2.setEditable(false); t1.addTextListener(this); }
  • 90. public void textValueChanged(TextEvent e) { t2.setText(t1.getText()); } public static void main(String[] args) { TextListenerExample tl= new TextListenerExample(); tl.setTitle("Text Event...."); tl.setSize(300,300); tl.setLayout(null); tl.setVisible(true); } }
  • 91. 7. WindowListener interface : • The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent. • The WindowListener interface is found in java.awt.event package. • Methods of WindowListener interface are given below: 1. windowActivated(WindowEvent e); 2. windowClosed(WindowEvent e); 3. windowClosing(WindowEvent e); 4. windowDeactivated(WindowEvent e); 5. windowDeiconified(WindowEvent e); 6. windowIconified(WindowEvent e); 7. windowOpened(WindowEvent e);
  • 92. import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class WindowExample extends Frame implements WindowListener { WindowExample() { // adding WindowListener to the frame addWindowListener(this); // setting the size, layout and visibility of frame setSize (400, 400); setLayout (null); setVisible (true); }
  • 93. public static void main(String[] args) { new WindowExample(); } public void windowActivated (WindowEvent arg0) { System.out.println("activated"); } public void windowClosed (WindowEvent arg0) { System.out.println("closed"); } public void windowClosing (WindowEvent arg0) { System.out.println("closing"); dispose(); } public void windowDeactivated (WindowEvent arg0) { System.out.println("deactivated"); }
  • 94. public void windowDeiconified (WindowEvent arg0) { System.out.println("deiconified"); } public void windowIconified(WindowEvent arg0) { System.out.println("iconified"); } public void windowOpened(WindowEvent arg0) { System.out.println("opened"); } }
  • 95. • The windowActivated() and windowDeactivated() methods are invoked when a window is activated or deactivated, respectively. • If a window is iconified, the windowIconified() method is called. • When a window is deiconified, the windowDeiconified() method is called. • When a window is opened or closed, the windowOpened() or windowClosed() methods are called, respectively. • The windowClosing() method is called when a window is being closed.
  • 96. 3.4. Inner classes : Inner classes are the nested classes. That means these are the classes that are defined inside the other classes. Syntax, Access_modifier class OuterClass { //code Access_modifier class InnerClass { //code } }
  • 97. Properties of Inner classes : • The outer class can inherit as many number of inner class objects as it wants. • If the outer class and the curresponding inner class both are public than any other class can create an instance of this inner class. • The inner class objects do not get instantiated with an outer class object. • The outer class can call the private methods of inner class. • Inner class mode has free access to all elements of the outer class object that contains it. • If the inner class has a variable with same name then the outer class’s variable can be accessed like this : outerclassname.this.variable_name
  • 98. Types of Inner classes : There are four types of inner classes : 1. Static Member Classes 2. Member Classes 3. Local Classes 4. Anonymous Classes