Professional Documents
Culture Documents
UNIT-5
Applets and Event Handling
Introduction
• Applets are small Java programs that are embedded in Web pages, which are executed and
displayed in java browser.
• They can be transported over the Internet from one computer (web server) to another (client
computers).
• Applets are used to provide inter-active features to the web applications.
• Applets are able to include animations, playing games, audio and video media playing etc.,
• Applet is a predefined class available in “java.applet” package.
• Applets don’t use the main() method, but when they are load, automatically call certain
methods (init, start, paint, stop, destroy).
• They cannot read from or write to the files on local computer.
• They cannot communicate with other servers on the network.
• They cannot run any programs from the local computer.
• They are restricted from using libraries from other languages.
• The above restrictions ensure that an Applet cannot do any damage to the local system.
Advantages of Applet:
• 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.
Applet Application
Applet needs explicit installation on the local
Application must run on local machine
machine.
Applets don’t use the main() method ,and start its Application starts its execution with
execution with init() method main()method.
Applet must run with GUI Application can run with or without GUI
Applet cannot read from or write to the files on local Applications can read from or write to the files on
computer. local computer.
They are restricted from using libraries from other Applications can use libraries from other
languages. languages.
Creating an Applet:
A) In this type we have to run the html page and call the java code(the applet program)
1) create separate java file for applet and compile it.
2) create separate html file
3) embed applet tag in it
4)open the html file in any browser .
FirstApplet.java
import java.applet.Applet;
import java.awt.*;
sample.html
<html>
<body>
<h1>Hi, This is My First Applet</h1>
<applet code="FirstApplet.class" width="500" height="200">
</applet>
</body>
</html>
Open the html file through a browser and the applet program should run through web browser.
Output:
2) In this type applet code is embedded into a java code, open it with using appletviewer tool.
FirstApplet.java
import java.applet.Applet;
import java.awt.*;
/*
<applet code="FirstApplet.class" width="500" height="200">
</applet>
*/
> appletviewer FirstApplet.java and you would be able to see the output on appletviewer
Output:
Applet Skeleton:
• This is the skeleton format used by the applet code
• In order to control the execution of the applets, following are the methods defined by the applet
o 1)init()
o 2)start()
o 3)stop()
o 4)destroy()
• One more method is defined by the awt component class which is
paint()
• These 5 methods can be assembled into skeleton as follows:
DemoApplet.java
import java .awt.*;
import java.applet.*;
/*
<applet code="DemoApplet.class" height="200" width="200">
</applet>
*/
public class DemoApplet extends Applet
{
public void init() {
System.out.println("...Applet Initialized");
}
public void start() {
System.out.println("...Applet started");
}
public void stop() {
System.out.println("...Applet stopped");
}
public void destroy() {
System.out.println("...Applet destroyed");
}
public void paint(Graphics g) {
System.out.println("...Painting applet...");
g.drawString("Sample Applet",30,30);
}
}
Output:
In command prompt:
In appletviewer:
ParamApplet.java
Output:
DisplayImage.java
import java.awt.*;
import java.applet.*;
/*
<applet code=”DisplayImage.class” width=”400” height=”300” >
</applet>
*/
public class DisplayImage extends Applet {
Image pict;
public void init() {
pict = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(pict, 30,30, this);
}
}
Output:
1. PolyApplet.java :
import java.applet.*;
import java.awt.*;
/*
<applet code="PolyApplet.class"
width="200" height="150">
</applet>
*/
2. LineGraphApplet.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="LineGraphApplet.class"
width="400"
height="150">
</applet>
*/
Example :
What is Event?
•An “event” is happened every time, when a user interacts with a ”user interface”.
•For example,
– when a user pushes a button,
– types a character in text box.
– Click the mouse button
– Selects an item in list box
– Selects a radio button etc.,
Event-Introduction
•We have done enough of objects and classes by now.
•An object resides in a particular state until it is made to transit to other state.
•This transition occurs due to an event.
•For example, we want an object to invoke a function when an action is generated, e.g.
– pressing a key on the keyboard,
– moving the mouse,
– clicking on a button, etc.
•The object which generates the event, i.e. the source of the event is known as the event generator.
Event Sources (Components) :
•Component class objects are visible in GUI interface, and user can perform some action with
interacting with the components.
•Containers are used to hold the components to display in the GUI
Different Gui class hierarchy in AWT:
1) The event model is based on the Event Source and Event Listeners.
2) Event Listener is an object that receives the messages / events.
3) The Event Source is any object which creates the message / event.
4) The Event Delegation model is based on – The Event Classes, The Event Listeners, Event Objects.
Steps involving in GUI Programming:
• Create object of container
• Set the layout of the container
• Add the objects of components to the container
• Override the event handler methods of event listeners against the action of the users
• Register the appropriate listener object with the components
Mechanism involved in Event Handling:
• Event Delegation model is based on the concept of an 'Event Source' and 'Event Listeners'.
• Any object that generates events due to user interaction is called an Event Source
• Ex : Button, Textbox, list,
• Any object that is interested in receiving messages (or events ) is called an Event Listener.
• Ex: ActionEvent, KeyEvent, MouseEvent etc.,
• We write the reaction for the action of user, by overriding the method of EventListener ( called
Event Handler methods).
• Now the Event source registers with Event Listener.
• Event source generates corresponding Event Object due to user’s action on the Event source
component.
• The Event object generated by Event source is received by Event listener which is registered with the
Event source earlier.
• Now Event Listener executes the Event handler as the reaction against the action by the user.
ActionEvent:
•This event is generated by a component (such as a Button) when the component-specific action
occurs (such as click).
•The event is passed to an ActionListener object which is registered to receive the event notification
using the component’s addActionListener method.
•The event handler method is actionPerformed(), will be executed as event handler.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="EventDemo.class" width="400" height="150">
</applet>
*/
public class EventDemo extends Applet
{
public void init()
{
// setting layout to the container.
setLayout(new FlowLayout());
// creating component.
Button b1 = new Button("Change Color");
// adding component to the container.
add(b1);
// registering listener to component.
b1.addActionListener(new MyListener());
}
}
class MyListener implements ActionListener
{
// overriding event handler method
public void actionPerformed(ActionEvent ae)
{
// creating random color
int r = (int)(Math.random()*255);
int g = (int)(Math.random()*255);
int b = (int)(Math.random()*255);
// applying random color to background of container
Component cp =(Component) ae.getSource();
Container cn = (Container) cp.getParent();
cn.setBackground(new Color(r,g,b));
}
}
Output:
KeyEvent :
• KeyEvent is an event which indicates that a keystroke occurred in a component.
– public class KeyEvent extends InputEvent
• is generated by component object (such as a text field, Applet, Frame) when a key is pressed,
released, or typed.
• The event is passed to a KeyListener object which is registered to receive the event notification
using the component’s addKeyListener method.
Program:
KeyEventsDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEventsDemo.class" width="400" height="200">
</applet>
*/
public class KeyEventsDemo extends Applet implements KeyListener
{
TextField t1;
int key;
String msg = "";
public void init() {
Label lname = new Label( "Enter some text : ");
t1 = new TextField(12);
add(lname);
add(t1);
t1.addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
key = ke.getKeyCode();
msg = "Key Down : " + (char) key;
repaint();
}
public void keyReleased(KeyEvent ke) {
key = ke.getKeyCode();
msg = "Key Up : " + (char)key;
repaint();
}
public void keyTyped(KeyEvent ke) {}
public void paint(Graphics g) {
showStatus(msg);
}
}
Output:
MouseEvent :
• It is an event which indicates that a mouse action occurred in a component.
• A mouse action occurs in a particular component if and only if the mouse cursor is over the
defined part of the component’s bounds when the action happens.
– public class MouseEvent extends InputEvent
• There are eight types of mouse events defined in the MouseEvent class.
Methods in the class MouseEvent:
int getButton()
Returns which, if any, of the mouse buttons has changed state.
int getClickCount()
Returns the number of mouse clicks associated with this event.
static String getMouseModifiersText(int modifiers)
Returns the modifier keys and mouse buttons, during the event, such as "Shift", or "Ctrl+Shift".
int getX()
Returns the horizontal x position of the event relative to the source component.
int getY()
Returns the vertical y position of the event relative to the source component.
Program:
MouseMotionDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseMotionDemo.class" width="300" height="200">
</applet>
*/
public class MouseMotionDemo extends Applet implements MouseMotionListener
{
int mx = 0,my = 0;
public void init() {
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me) {
mx = me.getX();
my = me.getY();
repaint();
}
public void mouseMoved(MouseEvent me) {
mx = me.getX();
my = me.getY();
repaint();
}
public void paint(Graphics g) {
g.drawString( "*(" + mx + ", " + my + ")",mx,my);
}
}
Output:
•The adjustment events are generated by Adjustable objects like scroll bar.
Methods of AdjustmentEvent :
Program to demonstrate Adjustment event with scrollbar control:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SBDemo.class" width="300" height="200">
</applet>
*/
public class SBDemo extends Applet
implements AdjustmentListener{
String msg = "";
Scrollbar hsb;
public void init() {
hsb = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,200);
add(hsb);
hsb.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
public void paint(Graphics g) {
int r = hsb.getValue();
msg = "Horizontal: " + r;
g.drawString(msg,6,160);
g.drawOval(130,100,r,r);
}
}
Output:
FocusEvent :
ItemEvent :
•It is an event which shows whether an item was selected or de-selected.
– public class ItemEvent extends AWTEvent
•This event is generated by an ItemSelectable object (such as a List), where the event is generated
when an item of the list is either selected or de-selected.
•The event generated is passed to every ItemListener object which is registered to receive such
events.
•The method addItemListener() is used for this registration process.
Program to demonstrate ItemEvent with Checkbox control:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ItemEventDemo" width="300" height="200">
</applet>
*/
public class ItemEventDemo extends Applet implements ItemListener
{
public void init() {
setLayout(new FlowLayout());
CheckboxGroup cp = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Large",cp,true);
Checkbox cb2 = new Checkbox("Medium",cp,false);
Checkbox cb3 = new Checkbox("Small",cp,false);
add(cb1);
add(cb2);
add(cb3);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
showStatus(ie.getItem() + " got selected!");
}
}
Output:
TextEvent :
•This event indicates the change in the object’s text.
– public class TextEvent extends AWTEvent
•This event is generated by an object (such as a TextComponent) whenever its text changes. The
event is passed to every TextListener object which is registered to receive such events.
The method addTextListener() is used for this registration process.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="TextEventDemo.class" width="400" height="150">
</applet>
*/
public class TextEventDemo extends Applet implements TextListener
{
public void init()
{
add(new Label("Enter some text : "));
TextField t1 = new TextField(15);
t1.addTextListener(this);
add(t1);
}
public void textValueChanged(TextEvent ae)
{
TextField t = (TextField)ae.getSource();
showStatus("You typed: " + t.getText());
}
}
Output:
Inner classes:
• An inner class is one that is declared entirely in the body of another class or interface.
• The class, which is nested, can only exist as long as the enveloping class exists.
• So, the scope of nested class is limited to the scope of enveloping class.
• Types of inner classes:
• Static nested class
• Non static nested class( Inner class)
• Local class
• Anonymous class
Output:
Output:
Difference between Top level class and anonymous inner class:
Adapter classes :
• Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers.
• 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.
• You can define a new class to act as an event listener by extending one of the adapter classes
and implementing only those events in which you are interested.
Output:
List of questions asked in old question papers:
PART-A
PART-B
1. a) What is the role of event listeners in event handling? List the Java event listeners
b) Write an applet to display the mouse cursor position in that applet window.
2. a) Explain delegation event model in detail.
b) Write an applet to display a smiley with a greeting message to the user.
3. a) What is an applet? Explain its life cycle.
b) Write a program to handle mouse events and mouse motion events.
4. a) Discuss the applet structure and compare it with application structure.
b) Write a program to handle keyboard events.
5. a) Discuss about different event classes.
b) Write a java program using listeners for handling keyboard events
6. a) Briefly explain about applet life cycle.
b) Discuss about one modern mechanism to handle events.
7. a) What are the problems with native methods?
b) Discuss about java.awt.event. InputEvent class.
8. a) Write a simple applet program to display a string “India won by 6 wickets”.
b) Discuss about java.awt.event.ActionEvent class.
9. a) Discuss about java.awt.event.keyEvent class.
b) Develop a java code that keeps the count of right clicks of mouse.
10. a) What are the sources of Event? Discuss.
b) Write a java program using listeners for handling mouse events
11. a) Write a Java program to create a combo box which includes list of subjects. Copy the subjects in
text field on click using applet.
b) Differentiate between init() and start() methods with examples.
12. a) Write Applets programs to accomplish the following tasks:
i) Drawing polygons ii) Drawing a line graph.
b) Can applet class have a constructor? Justify your answer with proper explanation and example.
13. a) Write an applet program that has different shapes in it.
b) Explain action event with suitable example.
ASSIGNMENT: UNIT-5
PART-A
a) "Java class can be used both as an applet as well as an application" - Support this statement with an
example.
b) What are the ways in which we can pass parameters to the applet?
c) What is an event? What methods are available to handle events in java?
d) What is source and listener in java event handling?
e) What are the advantages of event driven programming?
f) Compare nested class with inner class. Give examples for each
g) What is an adapter class? Give any two examples for it.
PART-B
Programs:
1) Assume that you have a Simple Applet that displays a message. Write a HTML text file to execute
that applet in web browser.
2) Write an applet to display the mouse cursor position in that applet window.
3) Write an applet to display a smiley with a greeting message to the user.
4) Write a program to handle mouse events and mouse motion events.
5) Develop a java code that keeps the count of right clicks of mouse.
. 6) Write a Java program to create a combo box which includes list of subjects. Copy the subjects in
text field on click using applet.
7) Write Applets programs to accomplish the following tasks:
i) Drawing polygons. ii) Drawing a line graph.