0% found this document useful (0 votes)
11 views45 pages

AJP Chapter 3

Uploaded by

binesol132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views45 pages

AJP Chapter 3

Uploaded by

binesol132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter 3

Event Handling
Made By

Mrs. Smita Kuldiwar

Date:- 24/08/2020
What is an Event?

For example, clicking on a


Change in the state of an button, moving the mouse,
entering a character through
object is known as event
keyboard, selecting an item
i.e. event describes the Events are generated as from list, scrolling the page are
change in state of source. result of user interaction the activities that causes an
with the graphical user event to happen.
interface components.
• The events can be broadly classified into two categories:
• 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.
Types of • For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item
Event from list, scrolling the page etc.
• Background Events - Those events that require the
interaction of end user are known as background events.
• Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the
example of background events.
• 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
What is known as event handler that is executed
Event when an event occurs.
• Java Uses the Delegation Event Model to
Handling? handle the events.
• This model defines the standard mechanism
to generate and handle the events. Let's
have a brief introduction to this model.
• Source - The source is an object on which event
occurs. Source is responsible for providing
The information of the occurred event to it’s handler.
Delegation • Java provide as with classes for source object.
• Listener - It is also known as event handler. Listener
Event Model is responsible for generating response to an event.
has the • From java implementation point of view the listener
is also an object.
following key • Listener waits until it receives an event. Once the
participants event is received , the listener process the event and
then returns.
namely:
Delegation Event Model

Listener 1 Take action 1

Listener 2 Take action 2

Event Source
Listener 3 Take action 3

Register the Listener 4 Take action 4


event
• 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.
• The advantage of this design is that the application logic that processes events
is cleanly separated from the user interface logic that generates those events.
Delegation • A user interface element is able to “delegate” the processing of an event to a
separate piece of code.

event model • 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.
Previously, an event was propagated up the containment hierarchy until it was
handled by a component.
• This required components to receive events that they did not process, and it
wasted valuable time.
• The delegation event model eliminates this overhead.
• The User clicks the button and the event is
generated.
• Now the object of concerned event class is
Steps created automatically and information about
involved in the source and the event get populated with
in same object.
event • Event object is forwarded to the method of
handling registered listener class.
• the method is now get executed and returns.
Event Listener
• The events generated by the GUI components are handled by a
special group of interfaces known as “listeners”.
• A listener is an object that is notified when an event occurs.
• Changing the state of an object is known as an event. For example,
click on button, dragging mouse etc. The java.awt.event package
provides many event classes and Listener interfaces for event
handling.

Source Event Listener

Fig. Event Listener


Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and
MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Action Listener for classes
• Button
• public void addActionListener(ActionListener a){}
• MenuItem
• public void addActionListener(ActionListener a){}
• TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
• TextArea
• public void addTextListener(TextListener a){}
• Checkbox
• public void addItemListener(ItemListener a){}
• Choice
• public void addItemListener(ItemListener a){}
• List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}
Java AWT Button Example with ActionListener
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();
} }
• 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. It has only one
ActionListener method: actionperformed().
Interface for actionPerformed() method
Action Event • The actionPerformed() method is invoked
automatically whenever you click on the
registered component.
• public abstract void actionPerformed(Action
Event e);
The common approach is to implement the
ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements Action
How to write Listener
ActionListener 2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass
);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){ }
ActionListener Example: On Button click
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example"); Output:
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this); f.add(b); f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint."); } }
We can also use the anonymous class to
implement the ActionListener. It is the shorthand
way, so you do not need to follow the 3 steps:
Java b.addActionListener(new ActionListener()
ActionListener {
Example: Using public void actionPerformed(ActionEvent e)
Anonymous {
class tf.setText("Welcome to Javatpoint.");
}
});
Let us see the full code of ActionListener using anonymous
class.
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) { OUTPUT:
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50,150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint."); }
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
The Java MouseListener is notified whenever you
change the state of mouse. It is notified against
MouseEvent.

2.
The MouseListener interface is found in
MouseListener java.awt.event package.
Interface

It has five methods.


The signature of 5 methods found in MouseListener
interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
Methods of 2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
MouseListener
4. public abstract void mousePressed(MouseEvent e);
interface
5. public abstract void mouseReleased(MouseEvent e);
MouseListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample(){
addMouseListener(this);
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true); }
MouseListener Example cont…
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked"); }
public void mouseEntered(MouseEvent e) { output:-
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(); } }
MouseListener Example 2
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this); OUTPUT:-
setSize(300,300);
setLayout(null);
setVisible(true); }
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30); }
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseListenerExample2();
} }
• The MouseMotionListener is notified whenever you
move or drag mouse.
• It is notified against MouseEvent. The
MouseMotionListener interface is found in
java.awt.event package.
• It has two methods
3.
MouseMotionListen
Methods of MouseMotionListener interface
er Interface
• The signature of 2 methods found in
MouseMotionListener interface are given below:
• public abstract void mouseDragged(MouseEvent e);

• public abstract void mouseMoved(MouseEvent e);


MouseMotionListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300); OUTPUT
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
} }
MouseMotionListener Example 2
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Paint extends Frame implements MouseMotionListener{
Label l;
Color c=Color.BLUE; OUTPUT
Paint(){
l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true); }
public void mouseDragged(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20); }
public void mouseMoved(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY()); }
public static void main(String[] args) {
new Paint(); } }
• The ItemListener is notified whenever you click on the
checkbox. It is notified against ItemEvent.
• The ItemListener interface is found in java.awt.event
package.
4.ItemListener • It has only one method: itemStateChanged().
Interface itemStateChanged() method:-
• The itemStateChanged() method is invoked automatically
whenever you click or unclick on the registered checkbox
component.
public abstract void itemStateChanged(ItemEvent e);
ItemListener Example
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label; OUTPUT
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);
ItemListener Example cont…
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();
}
}
• 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. It has three methods.
KeyListener Methods of KeyListener interface
Interface • The signature of 3 methods found in KeyListener
interface are given below:
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
KeyListener Example
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);
}
KeyListener Example cont…
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");
}

public static void main(String[] args) {


new KeyListenerExample();
}
}
Textfield Example
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
Textfield Example cont…
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e) { OUTPUT
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1 );
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b; }
String result=String.valueOf(c);
tf3.setText(result); }
public static void main(String[] args) {
new TextFieldExample();
} }
• 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
The signature of 7 methods found in WindowListener interface
WindowListener are given below:
• public abstract void windowActivated(WindowEvent e);
Interface • public abstract void windowClosed(WindowEvent e);
• public abstract void windowClosing(WindowEvent e);
• public abstract void windowDeactivated(WindowEvent e);
• public abstract void windowDeiconified(WindowEvent e);
• public abstract void windowIconified(WindowEvent e);
• public abstract void windowOpened(WindowEvent e);
WindowListener Example
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener{
WindowExample(){
addWindowListener(this);
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");
}
WindowListener Example
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");
} }
Adapter Classes
• Adapter classes provide the default implementation of listener interfaces.
• If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
java.awt.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener
WindowAdapter Example1
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{ OUTPUT
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
} });
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
} }
MouseAdapter Example2
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f; Output:
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
} }
• We can close the AWT Window or Frame by
calling dispose() or System.exit() inside windowClosing()
method. The windowClosing() method is found
in WindowListener interface and WindowAdapter class.
• The WindowAdapter class implements WindowListener
interfaces. It provides the default implementation of all the 7
How to close methods of WindowListener interface. To override the
windowClosing() method, you can either use WindowAdapter
class or WindowListener interface.
AWT • If you implement the WindowListener interface, you will be
Window forced to override all the 7 methods of WindowListener
interface. So it is better to use WindowAdapter class.
There are many ways to override windowClosing() method:
• By anonymous class
• By inheriting WindowAdapter class
• By implementing WindowListener interface
Close AWT Window Example 1: Anonymous class
import java.awt.*;
import java.awt.event.*;
public class WindowExample extends Frame{
WindowExample(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WindowExample();
}
Close AWT Window Example 2: extending WindowAdapter
import java.awt.*;
import java.awt.event.*;
public class AdapterExample extends WindowAdapter{
Frame f;
AdapterExample(){
f=new Frame();
f.addWindowListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
f.dispose();
}
public static void main(String[] args) {
new AdapterExample();
} }
Close AWT Window Example 3: implementing
WindowListener
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener{
WindowExample(){
addWindowListener(this); OUTPUT
setSize(400,400);
setLayout(null);
setVisible(true); }
public static void main(String[] args) {
new WindowExample(); }
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
dispose(); }
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent arg0) {} }
Text Listener Interface

• Class TextEvent. A semantic event which indicates that an


object's text changed. This high-level event is generated by an object
(such as a TextComponent) when its text changes. The event is passed
to every TextListener object which registered to receive
such events using the component's addTextListener method.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy