Unit 4
Unit 4
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
focusGained()
FocusEvent Component FocusListener
focusLost()
keyTyped()
KeyEvent Text component KeyListener keyPressed()
keyReleased()
mousePressed()
mouseEntered()
MouseEvent Mouse MouseListener
mouseExited ()
mouseReleased()
mouseMoved()
MouseMotionListener
MouseWheelEvent Mouse Wheel mouseDragged()
MouseWheelListener
mouseWheelMoved()
windowActivated()
windowDeActivated()
WindowEvent Window WindowListener
windowOpened()
windowClosed()
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( )
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");
}
}
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
}
}
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);
}
}
➢ 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:
// 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;
O/P: