0% found this document useful (0 votes)
16 views53 pages

File 1707213348 0003311 4 Eventhandling Updated

The document provides an overview of event handling in Java, explaining what events are, the types of events (foreground and background), and the event handling mechanism including sources and listeners. It details the steps involved in event handling, various Java event classes and listener interfaces, and examples of implementing event handling using ActionListener, KeyListener, MouseListener, and WindowListener. Additionally, it covers the methods associated with these listeners and provides code examples for practical understanding.
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)
16 views53 pages

File 1707213348 0003311 4 Eventhandling Updated

The document provides an overview of event handling in Java, explaining what events are, the types of events (foreground and background), and the event handling mechanism including sources and listeners. It details the steps involved in event handling, various Java event classes and listener interfaces, and examples of implementing event handling using ActionListener, KeyListener, MouseListener, and WindowListener. Additionally, it covers the methods associated with these listeners and provides code examples for practical understanding.
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/ 53

EVENT HANDLING

1
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.

2
Types of Event
 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. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an
item 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.
3
What is 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. The Delegation Event
Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible
for providing information of the occurred event to it's handler. Java provide
as with classes for source object.

 Listener - It is also known as event handler. Listener is responsible for


generating response to an event. From java implementation point of view the
listener is also an object. Listener waits until it receives an event. Once the
event is received , the listener process the event an then return

4
Steps involved in event handling
 The User clicks the button and the event is
generated.
 Now the object of concerned event class is
created automatically and information about the
source and the event get populated with in same
object.
 Event object is forwarded to the method of
registered listener class.
 the method is now get executed and returns

5
Event and Listener (Java Event
Handling)

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

6
Java Event classes and Listener
interfaces

7
Steps to perform Event Handling

Register the component with the Listener

8
Registration Methods
 For registering the component with the Listener, many classes provide the registration methods.

 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) 9
Java Event Handling Code

We can put the event handling code into


one of the following places:

 Within class
 Other class
 Anonymous class

10
Java event handling by implementing 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(); 11
 } }
Java event handling by outer class
 import java.awt.*;
 import java.awt.event.*;
 class AEvent2 extends Frame{
 TextField tf;
 AEvent2(){
 //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
 Outer o=new Outer(this);
 b.addActionListener(o);//passing outer class instance
 //add components and set size, layout and visibility
 add(b);add(tf);
 setSize(300,300);
 setLayout(null);
 setVisible(true);
 }
 public static void main(String args[]){
 new AEvent2();
 }
12
 }
 import java.awt.event.*;
 class Outer implements ActionListener{
 AEvent2 obj;
 Outer(AEvent2 obj){
 this.obj=obj;
 }
 public void actionPerformed(ActionEvent e){
 obj.tf.setText("welcome");
 }
 }

13
Java event handling by anonymous class
 import java.awt.*;
 import java.awt.event.*;
 class AEvent3 extends Frame{
 TextField tf;
 AEvent3(){
 tf=new TextField();
 tf.setBounds(60,50,170,20);
 Button b=new Button("click me");
 b.setBounds(50,120,80,30);

 b.addActionListener(new ActionListener(){
 public void actionPerformed(){
 tf.setText("hello");
 }
 });
 add(b);add(tf);
 setSize(300,300);
 setLayout(null);
 setVisible(true);
 }
 public static void main(String args[]){
 new AEvent3();
Java 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.
It has only one method: actionPerformed().

The actionPerformed() method is invoked automatically


whenever you click on the registered component.

 public abstract void actionPerformed(ActionEvent e);

15
Java 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. It has three
methods.
Methods of KeyListener 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);
20
Example- Key Listener
 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");
 }
 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();
 }
 } 21
Java KeyListener Example 2: Count Words & Characters
 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,200,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) {}
 public void keyReleased(KeyEvent e) {
 String text=area.getText();
 String words[]=text.split("\\s");
 l.setText("Words: "+words.length+" Characters:"+text.length());
 }
 public void keyTyped(KeyEvent e) {}

 public static void main(String[] args) {


 new KeyListenerExample();
 }
 } 22
Java MouseListener Interface
The Java MouseListener is notified whenever you change the
state of mouse. It is notified against MouseEvent. The
MouseListener interface is found in java.awt.event package. It
has five methods.

 Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface
are given below:
 public abstract void mouseClicked(MouseEvent e);
 public abstract void mouseEntered(MouseEvent e);
 public abstract void mouseExited(MouseEvent e);
 public abstract void mousePressed(MouseEvent e);
 public abstract void mouseReleased(MouseEvent e);
23
Java MouseListener Example
 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();
 } 24
 }
Java MouseListener Example 2
 import java.awt.*;
 import java.awt.event.*;
 public class MouseListenerExample2 extends Frame implements MouseListener{
 MouseListenerExample2(){
 addMouseListener(this);

 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();
 } 25
 }
Java 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. It has two methods.

Methods of MouseMotionListener 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);

26
Java MouseMotionListener Example
 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(),20,20);
 }
 public void mouseMoved(MouseEvent e) {}

 public static void main(String[] args) {


 new MouseMotionListenerExample();
 }
 }
27
Java 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. It has three methods.

Methods of WindowListener interface

 The signature of 7 methods found in WindowListener interface are given below:


 public abstract void windowActivated(WindowEvent e);
 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);

28
Java 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");
 }
 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");
 } }
Java Adapter Classes

 Java 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.

 The adapter classes are found


in java.awt.event, java.awt.dnd and javax.swing
.event packages.
30
java.awt.event Adapter classes

31
javax.swing.event Adapter classes

32
Java WindowAdapter Example
 import java.awt.*;
 import java.awt.event.*;
 public class AdapterExample{
 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();
 }
 }

33
Java MouseAdapter Example
 import java.awt.*;
 import java.awt.event.*;
 public class MouseAdapterExample extends MouseAdapter{
 Frame f;
 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();
 }
 } 34
Java KeyAdapter Example
 import java.awt.*;
 import java.awt.event.*;
 public class KeyAdapterExample extends KeyAdapter{
 Label l;
 TextArea area;
 Frame f;
 KeyAdapterExample(){
 f=new Frame("Key Adapter");
 l=new Label();
 l.setBounds(20,50,200,20);
 area=new TextArea();
 area.setBounds(20,80,300, 300);
 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();
 String words[]=text.split("\\s");
 l.setText("Words: "+words.length+" Characters:"+text.length());
 }

 public static void main(String[] args) {


 new KeyAdapterExample();
 }
 }
35
Java Applet

Applet is a special type of program that is embedded in the webpage to


generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

36
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java
application, including the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.

37
Hierarchy of Applet

38
Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

39
Lifecycle methods for Applet:

For creating any applet java.applet. Applet class must be


inherited. It provides 4 life cycle methods of applet.

 public void init(): is used to initialized the Applet. It is


invoked only once.
 public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
 public void destroy(): is used to destroy the Applet. It is
invoked only once.

40
Four methods in the Applet class gives you the framework on which you
build any serious applet −

 init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
 start − This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing
the applet after having gone off to other pages.
 stop − This method is automatically called when the user moves off the
page on which the applet sits. It can, therefore, be called repeatedly in the
same applet.
 destroy − This method is only called when the browser shuts down
normally. Because applets are meant to live on an HTML page, you should
not normally leave resources behind after a user leaves the page that
contains the applet.
 paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.
41
java.awt.Component class

The Component class provides 1 life cycle


method of applet.

 public void paint(Graphics g): is used to paint


the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.

42
How to run an Applet?

There are two ways to run an applet

 By html file.
 By appletViewer tool (for testing purpose).

43
Simple example of Applet by html file:
To execute the applet by html file, create an applet and
compile it. After that create an html file and place the applet
code in html file. Now click the html file.
 //First.java
 import java.applet.Applet;
 import java.awt.Graphics;
 public class First extends Applet{

 public void paint(Graphics g){


 g.drawString("welcome",150,150);
 }

 } 44
myapplet.html

 <html>
 <body>
 <applet code="First.class" width="300" height
="300">
 </applet>
 </body>
 </html>

45
Simple example of Applet by appletviewer
tool:
To execute the applet by appletviewer tool, create
an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is
for testing purpose only.
To execute the applet by appletviewer tool, write
in command prompt:
 c:\>javac First.java
 c:\>appletviewer First.java
46
 //First.java
 import java.applet.Applet;
 import java.awt.Graphics;
 public class First extends Applet{

 public void paint(Graphics g){


 g.drawString("welcome to applet",150,150);
 }

 }
 /*
 <applet code="First.class" width="300" height="300">
 </applet>
 */ 47
Displaying Image in Applet

Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.
Syntax of drawImage() method:
 public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

How to get the object of Image?

The java.applet.Applet class provides getImage() method that returns the


object of Image. Syntax:
 public Image getImage(URL u, String image){}

48
 import java.awt.*;
 import java.applet.*;

 public class DisplayImage extends Applet {


 Image picture;

 public void init() {


 picture = getImage(getDocumentBase(),"sonoo.jpg");
 }

 public void paint(Graphics g) {


 g.drawImage(picture, 30,30, this);
 }

 }

49
 <html>
 <body>
 <applet code="DisplayImage.class" width="300"
height="300">
 </applet>
 </body>
 </html>

50
EventHandling in Applet

 As we perform event handling in AWT or Swing,


we can perform it in applet also

51
Example of EventHandling in applet:
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 public class EventApplet extends Applet implements ActionListener{
 Button b;
 TextField tf;

 public void init(){


 tf=new TextField();
 tf.setBounds(30,40,150,20);

 b=new Button("Click");
 b.setBounds(80,150,60,50);

 add(b);add(tf);
 b.addActionListener(this);

 setLayout(null);
 }

 public void actionPerformed(ActionEvent e){


 tf.setText("Welcome");
 }
 }
52
myapplet.html

 <html>
 <body>
 <applet code="EventApplet.class" width="300
" height="300">
 </applet>
 </body>
 </html>

53

You might also like