0% found this document useful (0 votes)
17 views20 pages

Unit 4

This document covers event handling in Java, focusing on the delegation event model, event sources, listeners, and classes. It explains how applets work, their lifecycle, and the differences between applets and applications. Additionally, it provides examples of handling mouse and keyboard events, as well as the use of adapter classes for simplifying event listener implementations.

Uploaded by

23eg112a52
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)
17 views20 pages

Unit 4

This document covers event handling in Java, focusing on the delegation event model, event sources, listeners, and classes. It explains how applets work, their lifecycle, and the differences between applets and applications. Additionally, it provides examples of handling mouse and keyboard events, as well as the use of adapter classes for simplifying event listener implementations.

Uploaded by

23eg112a52
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/ 20

UNIT-4: Event Handling: Events, Event sources, Event classes, Event Listeners,

Delegation event model, handling mouse and keyboard events, Adapter classes.
Applets – Concepts of Applets, differences between applets and applications, life cycle
of an applet, create applets, passing parameters to applets.
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.

A user interface element is able to “delegate” the processing of an event to a separate piece of code.

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.

Events
In the delegation model, an event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause
events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.
Many other user operations could also be cited as examples. Events may also occur that are not directly caused by
interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware
failure occurs, or an operation is completed. You are free to define events that are appropriate for your application.
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 found in java.awt.event. For example, the
MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any
object may receive and process one or both of these events if it provides an implementation of this interface.

Event Classes:
Java defines several types of events.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its
one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ).
The getSource( ) method returns the source of the event. Its general form is shown here:
Object getSource( )
As expected, toString( ) returns the string equivalent of the event.
• EventObject is a superclass of all events.
• AWTEvent is a superclass of all AWT events that are handled by the delegation event model.
Its getID( ) method can be used to determine the type of the event.
The class AWTEvent, defined within the java.awt package, is a subclass of EventObject.

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavy weight i.e. its components are using the resources of underlying operating
system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The package java.awt.event defines many types of events that are generated by various user interface elements.
Class/source Events Interfaces/Listener Methods

ActionEvent Button,list ActionListener actionPerformed()

AdjustmentEvent Component AdjustmentListener adjustmentValueChanged()


componentResized()
componentMoved()
ComponentEvent Component ComponentListener
componentShown()
componentHidden()
componentAdded()
ContainerEvent Component ContainerListener
componentRemoved()

focusGained()
FocusEvent Component FocusListener
focusLost()

ItemEvent Check box, choice ItemListener itemStateChanged()

keyTyped()
KeyEvent Text component KeyListener keyPressed()
keyReleased()
mousePressed()
mouseEntered()
MouseEvent Mouse MouseListener
mouseExited ()
mouseReleased()
mouseMoved()
MouseMotionListener
MouseWheelEvent Mouse Wheel mouseDragged()
MouseWheelListener
mouseWheelMoved()

TextEvent Text Component TextListener textChanged()

windowActivated()
windowDeActivated()
WindowEvent Window WindowListener
windowOpened()
windowClosed()

Event Listener Interfaces:


The delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more
of the interfaces defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener and provides an
event object as its argument.
The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown
void actionPerformed(ActionEvent ae)
The KeyListener Interface
This interface defines three methods. 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 entered.
For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence:
key pressed and released.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

The MouseListener Interface


This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked.
When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The
mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Delegation Event Model:
Event delegation follows two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.
Remember that a source may generate several types of events. Each event must be registered separately. Also, an object
may register to receive several types of events, but it must implement all of the interfaces that are required to receive these
events.
Handling Mouse Events
To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces.
It displays the current coordinates of the mouse in the applet’s status window. Each time a button is pressed, the word
“Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a
button is clicked, the message “Mouse clicked” is displayed in the upperleft corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area.
When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged. Notice that the two
variables, mouseX and mouseY, store the location of the mouse when a mouse pressed, released, or dragged event occurs.
These coordinates are then used by paint( ) to display output at the point of these occurrences.
// Demonstrate the mouse event handlers
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
O/P:

The MouseEvents class extends Applet and implements both the MouseListener and MouseMotionListener interfaces. These
two interfaces contain methods that receive and process the various types of mouse events. Notice that the applet is both the
source and the listener for these events. This works because Component, which supplies the addMouseListener( ) and
addMouseMotionListener( ) methods, is a superclass of Applet. Inside init( ), the applet registers itself as a listener for mouse
events. This is done by using addMouseListener( ) and addMouseMotionListener( )

Handling Keyboard Events:


Implements the KeyListener interface. When a key is pressed, a KEY_PRESSED event is generated. This results in a call to
the keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and the
keyReleased( ) handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.
The following program demonstrates keyboard input. It echoes keystrokes to the applet
window and shows the pressed/released status of each key in the status window.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}

O/P:

Adapter Classes:
Java provides a special feature, called an adapter class- provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a
particular event listener interface.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ), which are the methods
defined by the MouseMotionListener interface. If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty implementation of mouseMoved( ) would handle the mouse
motion events for you.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AdapterDemo" width=300 height=100></applet>*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
} }
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}

commonly used adapter classes in java.awt.event


The program has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of MyMouseAdapter and
registers that object to receive notifications of mouse events. It also creates an instance of MyMouseMotionAdapter and
registers that object to receive notifications of mouse motion events.
MyMouseAdapter extends MouseAdapter and overrides the mouseClicked( ) method.
The other mouse events are silently ignored by code inherited from the MouseAdapter class. MyMouseMotionAdapter
extends MouseMotionAdapter and overrides the mouseDragged( ) method. The other mouse motion event is silently ignored
by code inherited from the MouseMotionAdapter class.

Applets – Concepts of Applets, differences between applets and applications, life cycle
of an applet, create applets, passing parameters to applets.
Applets :
The Applet class is contained in the java.applet package.

What is an applet?
Applet: A small Java program that can be inserted into a web page and run by loading that page in a browser.

An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed b y a
Java- compatible web browser.

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installe d, and
run as part of a web document.
Two Types of Applets:
➢ The first are those based directly on the Applet class.
➢ The second type of applets are those based on the Swing class JApplet. Swing applets use the Swing classes to provide the
GUI, easier-to-use user interface.
➢ JApplet inherits Applet, all the features of Applet are also available in JApplet.

➢ Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer.
➢ The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTMLfile.
➢ The standard applet viewer, called appletviewer, provided by the JDK.
➢ Execution of an applet does not begin at main( ).
/*<applet code="MyApplet" width=200 height=60></applet> */
The Methods Defined by Applet:
◼ void init( ) --> Called when an applet begins execution. It is the first method called for any applet.
◼ String getParameter(String paramName) --> Returns the parameter associated with paramName. null is returned if the
specified parameter is not found.
◼ void destroy( ) --> Called by the browser just before an applet is terminated. Your applet will override this method if it
needs to perform any cleanup prior to its destruction.
◼ void showStatus(String str) --> Displays str in the status window of the browser or applet viewer. If the browser does not
support a status window, then no action takes place.
◼ void start( ) --> Called by the browser when an applet should start (or resume) execution. It is automatically called after init( )
when an applet first begins.
◼ void stop( ) --> Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser
calls start( ).

In applet architecture, the user interacts with the applet when he or she wants. These interactions are sent to the applet as events
to which the applet must respond. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked
event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated.

Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. Default
implementations for all of these methods are provided.

paint( ) method, which is defined by the AWT Component class. It is called when the applet’s output must be re displayed.

These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkel" width=300 height=100> </applet> */
public class AppletSkel extends Applet
{
// Called first.
public void init()
{
// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
// start or resume execution
}
// Called when the applet is stopped.
public void stop()
{
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy()
{
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
// redisplay contents of window
}
}

Applet Initialization and Termination:


When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( )
The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called
once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen.
paint( )
The paint( ) method is called each time your applet’s output must be redrawn. paint( ) is also called when the applet begins
execution.
Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of
type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet
is running.
stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another
page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t
need to run when the applet is not visible.
destroy( )
The destroy( ) method is called when the environment determines that your applet needs to be removed completely from
memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before
destroy( ).
To output a string to an applet, use drawString( ), which is a member of the Graphics class. Typically, it is called from within
either update( ) or paint( ).
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y.

To set the background color of an applet’s window, use setBackground( ). void setBackground(Color newColor)
To set the foreground color use setForeground( ). void setForeground(Color newColor)

setBackground(Color.green);
setForeground(Color.red);

Ex:
import java.applet.*;
import java.awt.*;
/*<applet code="AppletDemo" width=100 height=200></applet> */
public class AppletDemo extends Applet
{
public void init()
{
setBackground(Color.green);
setForeground(Color.red);
}
public void paint(Graphics g)
{
g.drawString("Hello",100,100);
}
}

How Applets Differ from Applications:


Although both the Applets and stand-alone applications are Java programs, there are certain restrictions are imposed on Applets due to
security concerns:

➢ Applets don’t use the main() method, but when they are loaded, automatically call certain methods (init, start, paint, stop, destroy).
➢ They are embedded inside a web page and executed in browsers.
➢ Takes input through Graphical User Input ( GUI ).
➢ They cannot read from or write to the files on local computer.
➢ They cannot run any programs from the local computer.
➢ They are restricted from using libraries from other languages.

The above restrictions ensures that an Applet cannot do any damage to the local system.
1. Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for
embedding or downloading.

2. Applets can only be executed inside a java compatible web browser or appletviewer whereas Applications are executed at command line
by java.

3. After an applet arrives on the client, it has limited access to resources on local computer. Applications have no restriction to access
resources.

4. Applets don’t have the main() method as in applications. Instead they operate on an entirely different mechanism where they are
initialized by init(),started by start(),stopped by stop() or destroyed by destroy().

5. A Java Applet is made up of at least one public class that has to be subclasses from java.applet.Applet. Whereas, A Java application is
made up of a main() method declared as public static void that accepts a string array argument, along with any other classes that main()
calls.

Running an Applet
There are two ways in which you can run an applet:

⚫ Executing the applet within a Java-compatible browser.


⚫ Using a tool called , appletviewer. An applet viewer executes your applet in a window. This is generally the fastest
and easiest way to test your applet.
Passing Parameters to Applets:
The APPLET tag in HTML allows you to pass parameters to your applet.
To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String
object. Thus, for numeric and boolean values, you will need to convert their string representations into their internal formats.

// Use Parameters
import java.awt.*;
import java.applet.*;
/* <applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet
{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start()
{
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try
{
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
param = getParameter("leading");
try
{
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e)
{
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
// Display parameters.
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}
O/P:
Develop an applet in Java that receives an integer in one text field, and computes its
factorial Value and returns it in another text field, when the button named “Compute”is
clicked:

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*<applet code="Fact.class" height=300 width=300></applet>*/

public class Factorial extends Applet implements ActionListener


{
Label inputLable,outputLable;
TextField inputTextField,outputTextField;
Button btn;
public void init(){
inputLable=new Label("Enter any integer value: ");
inputTextField=new TextField(5);
btn=new Button("Calculate");
btn.addActionListener(this);
outputLable=new Label("Factorial of given integer number is ");
outputTextField=new TextField(10);
add(inputLable);
add(inputTextField);
add(btn);
add(outputLable);
add(outputTextField);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn)
{
int fact=fact(Integer.parseInt(inputTextField.getText()));
outputTextField.setText(String.valueOf(fact));
}
}
int fact(int f)
{
if(f==0)
return 1;
else
return f*fact(f-1);
}
}

O/P:

You might also like