You are on page 1of 40

Java Programming

UNIT-5
Applets and Event Handling

Topics covered in this unit:


• Applets:
– Applet class
– Applet structure
– Applet life cycle
– Sample Applet programs
• Event handling:
– Event Delegation Model
– Sources of event
– Event Listeners
– Adapter classes
– Inner classes

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.

There are two ways to run the applet:


• Using browser
• Using appletviewer tool
Applets can be included in HTML file by using APPLET tag. If you want to include applet tag in a program
itself then you have to include it by using a comment like
/*
<applet code=”classname” width=”200” height=”500”>
</applet>
*/

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.

Difference between Applet and application :

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:

To create an applet it is compulsory to import 2 packages which are


a) java.applet package and b) java.awt package to draw the applet in the paint method.

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.*;

public class FirstApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString("Hello World of Java!", 40, 30);
}
}

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>
*/

public class FirstApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString("Hello World of Java!", 40, 30);
}
}

To display the output using appletviewer we have to write

> appletviewer FirstApplet.java and you would be able to see the output on appletviewer

Output:

Methods in Applet class:

Life Cycle Methods :


– public void init ()
– public void start ()
– public void paint (Graphics)
– public void stop ()
– public void destroy ()
Also:
– public void repaint()
– public void update (Graphics)
– public void showStatus(String)
– public String getParameter(String)

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:

Applet Life Cycle:


When applets are loaded, they go through different phases or we can say different states and based
on those states, we can create applet state diagram i.e. applet life cycle. The different Applet states are
as follows.
 Born
 Running
 Idle
 Dead
These are the states of applet. In diagrammatic manner we can draw it as follow:
Applet States and life cycle methods:
• Initialisation – invokes init() – only once
– Invoked when applet is first loaded.
• Running – invokes start() – more than once
– For the first time, it is called automatically by the system after init() method execution.
– It is also invoked when applet moves from idle/stop() state to active state. For example,
when we return back to the Web page after temporary visiting other pages.
• Display – invokes paint() - more than once
– It happens immediately after the applet enters into the running state. It is responsible
for displaying output.
• Idle – invokes stop() - more than once
– It is invoked when the applet is stopped from running. For example, it occurs when we
leave a web page.
• Dead/Destroyed State – invokes destroy() - only once
– This occurs automatically by invoking destroy() method when we quite the browser.
Other methods in Applet:
The HTML APPLET Tag with all attributes:

Passing parameters to applet:


• We can communicate from the web page to Applet through passing parameters.
• We can include inner tag <param> to pass a string value.
• Ex:
/*
<applet code="ParamApplet.class" width="300" height="200">
<param name="msg" value="Have a nice day!">
<param name="user" value="Ravi kiran">
</applet>
*/

ParamApplet.java
Output:

Displaying Graphical Shapes in Applet (java.awt.Graphics) :


The java.awt.Graphics class contains many methods to draw different geometrical shapes
• public void drawString(String str, int x, int y): draws a specified string.
• public void drawRect(int x, int y, int width, int height): draws rectangle with width and height.
• public void fillRect(int x, int y, int width, int height): draws fill rectangle with the default color
• public void drawOval(int x, int y, int width, int height): draws oval with given width and height.
• public void fillOval(int x, int y, int width, int height): draws filled oval with color.
• public void drawLine(int x1, int y1, int x2, int y2): draws line with points(x1, y1) & (x2, y2).
• public boolean drawImage(Image img, int x, int y, ImageObserver observer): draws an image.
• public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): draws a circular or
elliptical arc.
• public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a
circular or elliptical arc.
• public void setColor(Color c): to set the graphics current color to the specified color.
• public void setFont(Font font): to set the graphics with a specified font.
Output:

Sample Applet programs:


a) 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:
o public Image getImage(URL u, String image);

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:

Write Applets programs to accomplish the following tasks:


i) Drawing polygons ii) Drawing a line graph.

1. PolyApplet.java :
import java.applet.*;
import java.awt.*;

/*
<applet code="PolyApplet.class"
width="200" height="150">
</applet>
*/

public class PolyApplet extends Applet


{
public void paint(Graphics g)
{
int xpoints[] = {25, 145, 25, 145, 25};
int ypoints[] = {25, 25, 145, 145, 25};
int npoints = 5;
g.drawPolygon(xpoints, ypoints, npoints);
}
}
Output:

2. LineGraphApplet.java

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

/*
<applet code="LineGraphApplet.class"
width="400"
height="150">
</applet>
*/

public class LineGraphApplet extends Applet


{
String text;
public void init() {
setBackground(Color.yellow);
setForeground(Color.red);
}
public void paint(Graphics g) {
int x1 = 30, y1 = 125;
int x2 = 70, y2 = 90;
int x3 = 250, y3 = 65;
int x4 = 325, y4 = 30;
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3));
g2.drawLine(x1,y1,x2,y2);
g2.drawLine(x2,y2,x3,y3);
g2.drawLine(x3,y3,x4,y4);
}
}
Output:
Event handling
What is GUI?
• A graphical user interface or GUI is
• a type of interface
• that allows users to interact with electronic devices
• through graphical icons and visual indicators such as secondary notation.

Example :

Elements of GUI Programming


• Components
Visual objects that appear on the screen
Example: Button, Checkbox, List, Text Field
• Containers
Specific objects which can hold other components
Example: Frame, Window, Applet
• Layouts
Control over the positioning of components within a container
Example: FlowLayout, BorderLayout, CardLayout
• Events
Responses to user actions
Example: ActionEvent, MouseEvent, KeyEvent, ItemEvent
• Graphics
Example: Lines, shapes, colors, fonts, etc.
Different GUI Components:

Two categories of Java Component classes:

– AWT – Abstract Windows Toolkit (java.awt package)


– The older version of the components
– Rely on “peer architecture”…drawing done by the OS platform on which the
application/applet is running
– Considered to be “heavy-weight”
– Swing (javax.swing package)
– Newer version of the components
– No “peer architecture”…components draw themselves
– Most are consdered to be “lightweight”

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:

Event Class Hierarchy in java.awt.event package:

Listener Classes in Java:


Event Delegation Model of 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.

Advantages of event driven programming:


• In Event Driven Programming, Workflow of the application follows through the actions generated
by users.
• Event handlers are used to separate the code of reactions generated against actions of users.
• GUI components are most suitable for event driven programming. Event Sources generates the
Event objects, System reacts with event handlers.
• Particularly, Java introduced Event delegation model which has the following advantages.
• Event-delegation model has two advantages over event-inheritance model.
• Event delegation model enables event handling by objects other than the ones that
generate the events.
• This allows a clean separation between a component's design and its use.
• It performs much better in applications where many events are generated.
• This performance improvement is due to event-delegation model does not have to be
repeatedly process unhandled events as is the case of the event-inheritance.

Events – Event Sources – EventListeners:

Event Classes in java.awt.event:


• ActionEvent: Generated when a button is pressed, a list item is double clicked, or a menu item is
selected.
• AdjustmentEvent: Generated when a scroll bar is manipulated.
• ComponentEvent: Generated when a component is hidden, moved, resized, or becomes visible.
• ContainerEvent: Generated when a component is added to or removed from a container.
• FocusEvent: Generated when a component gains or loses keyboard focus.
• InputEvent: Abstract super class for all component input event classes.
• ItemEvent: Generated when a check box or list item is clicked; also occurs when a choice
selection is made or a checkable menu item is selected or deselected.
• KeyEvent: Generated when input is received from the keyboard.
• MouseEvent: Generated when the mouse is dragged, moved, clicked, pressed, or released; also
generated when the mouse enters or exits a component.
• TextEvent: Generated when the value of a text area or text field is changed.
• WindowEvent: Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.

Some important Event Listeners and their abstract methods:


•ActionListener
– void actionPerformed(ActionEvent ae)
•AdjustmentListener
– void adjustmentValueChanged(AdjustmentEvent ae)
•FocusListener
– void focusGained(FocusEvent fe)
– void focusLost(FocusEvent fe)
•KeyListener
– void keyPressed(KeyEvent ke)
– void keyReleased(KeyEvent ke)
– void keyTyped(KeyEvent ke)
•MouseListener
– void mouseClicked(MouseEvent me)
– void mouseEntered(MouseEvent me)
– void mouseExited(MouseEvent me)
– void mousePressed(MouseEvent me)
– void mouseReleased(MouseEvent me)
•MouseMotionListener
– void mouseDragged(MouseEvent me)
– void mouseMoved(MouseEvent me)
•ItemListener
– void itemStateChanged(ItemEvent ie)
•WindowListener
– void windowActivated(WindowEvent we)
– void windowClosed(WindowEvent we)
– void windowClosing(WindowEvent we)
– void windowDeactivated(WindowEvent we)
– void windowDeiconified(WindowEvent we)
– void windowIconified(WindowEvent we)
– void windowOpened(WindowEvent we)

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:

Program to demonstrate MouseListener and MouseMotionListener:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents.class" width="300" height="200">
</applet>
*/
public class MouseEvents extends Applet implements MouseListener,MouseMotionListener
{
String msg = "";
int mouseX = 0,mouseY = 0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseExited(MouseEvent me){
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mouseEntered(MouseEvent me){
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "up";
repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + "," + me.getY());
}
public void paint(Graphics g) {
g.drawString(msg,mouseX,mouseY);
}
}
AdjustmentEvent :

•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 :

•This event is generated when a component gains or loses focus.


•There are two types of focus events: permanent and temporary.
– Permanent focus event occurs when the user explicitly changes focus from one
component to other, e.g. by pressing tab key.
– Temporary focus event occurs when the focus is lost due to operations like Window
deactivated. In this case, when the window will again be activated, the focus will be on
same component.

Program to demonstrate focus event with button control:


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="FocusEventDemo.class" width="400" height="150">
</applet>
*/
public class FocusEventDemo extends Applet implements FocusListener
{
public void init()
{
Button b1 = new Button("Button 1");
add(b1);
b1.addFocusListener(this);
Button b2 = new Button("Button 2");
add(b2);
}
public void focusLost(FocusEvent fe)
{
showStatus("Button lost focus");
}
public void focusGained(FocusEvent fe)
{
showStatus("Button got focus");
}
}
Output:

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.

Program to demonstrate text event with a text field:

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

Points regarding Non static nested class (Inner class):


• The inner class has access to all members of the enveloping class including protected and
private members.
• The enveloping class does not have direct access to nested class members. It is only through the
reference of inner class.
• An instance of inner class outside the enveloping class can only be created with an instance of
outer class.
• A method of inner class cannot be directly accessed by the object of outer class. The access is
through the object of inner class by a fully qualified name for accessing.

Advantages of inner classes:


• Inner classes represent a special type of relationship that is it can access all the members (data
members and methods) of outer class including private.
• Inner classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
• Code Optimization: It requires less code to write.

Types of Inner classes:


• Non-static inner class:
– A non-static class that is created inside a class but outside a method is called member
inner class.
– It has access to all members of the enveloping class including protected and private
members.
– An instance of inner class outside the enveloping class can only be created with an
instance of outer class.
• Static inner class:
– A static class i.e. created inside a class is called static nested class in java.
– It cannot access non-static data members and methods. It can be accessed by outer
class name.
– An inner class written inside the interface is automatically treated as static inner class.
• Local class:
– A class i.e. created inside a method is called local inner class in java.
– If you want to invoke the methods of local inner class, you must instantiate this class
inside the method.
• Anonymous Inner class:
– A class have no name is known as anonymous inner class.
– It should be used if you have to override method of class or interface.
– Java Anonymous inner class can be created by two ways:
• Class (may be abstract or concrete).
• Interface

Program to demonstrate Non-Static inner class:

Output:

Program to demonstrate Static Inner Class:


Output:

Difference between Non-static inner class and static inner class:

Non-static Inner class Static Inner class


To create object of non-static inner class, Object of Static inner class can be created even
before that we should create outer class object. without creating outer class object.
We cannot declare static members in non-static Inside static nested class, we can declare static
inner class members.
We cannot declare main() method in non-static We can declare main() method in static inner
inner class. class, and we can execute it directly from the
command prompt.
Inside the non-static inner class, we can access From static nested class, we can access only static
both static and non static members of outer members of outer class directly.
class directly.

Program to demonstrate Local Class:


Output:

Program to demonstrate Anonymous Inner Class:

Output:
Difference between Top level class and anonymous inner class:

Top level class Anonymous Inner class


Can extend only one class at a time. Can extend only one class at a time.
Can implement any no. of interfaces at a time. Can implement only one interface at a time.
Can extend a class and also can implement Can extend a class or can implement interface,
interface simultaneously. but not both simultaneously.
We can write constructor because we know the We cannot write constructor because anonymous
name of the class. inner class not having any name.

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.

List of Adapter classes and related Listener classes:

Program with Adapter class as anonymous inner class:


WindowEventDemo.java
import java.awt.*;
import java.awt.event.*;

public class WindowEventDemo extends Frame {


public WindowEventDemo() {
setSize(200,200);
add(new Label("Hello"),BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.out.println("Close Button is clicked..");
System.exit(0);
}
});
}
public static void main(String args[])
{
WindowEventDemo w1 = new WindowEventDemo();
w1.setVisible(true);
}
}

Output:
List of questions asked in old question papers:

PART-A

a) What are the differences between applet and application programs?


b) Assume that you have a Simple Applet that displays a message. Write a HTML text file to execute that
applet in web browser.
c) "Java class can be used both as an applet as well as an application" - Support this statement with an
example.
d) Describe the different stages in the life cycle of an Applet.
e) What are the ways in which we can pass parameters to the applet?
f) What is an event? What methods are available to handle events in java?
g) Explain in brief the event-handling mechanism in java with an example.
h) What is source and listener in java event handling?
i) What are the advantages of event driven programming?
j) Give the sources of action event and item event
k) Discuss about inner classes.
l) Compare nested class with inner class. Give examples for each
m) What is an adapter class? Give any two examples for it.

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

1. a) What is an applet? Explain its life cycle.


b) Can applet class have a constructor? Justify your answer with proper explanation and example.
2. a) Discuss the applet structure and compare it with application structure.
b) how parameters passed to applet from the web page? Give example.
3. a) Explain delegation event model in detail.
b) Discuss about different event classes.
4. a) Discuss about java.awt.event.keyEvent class.
b) What is the roll of listener class in event handling? List-out abstract methods of some Listener
classes.

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.

You might also like