0% found this document useful (0 votes)
5 views29 pages

Java Applet Basics and Lifecycle Guide

Uploaded by

tharunrowdy092
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Java Applet Basics and Lifecycle Guide

Uploaded by

tharunrowdy092
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Unit-4

[Link] Class
[Link] Handling
Applet
Applet is one kind of application program,
travelled via internet and can be executed on
client machine.
Applet is a special type of program that is
embedded in the webpage to generate the
dynamic content. It runs inside the browser and
works at client side.
Application Program=pure java code
Applet program= java code + HTML code

Advantages of Applet
There are many advantages of applet. They are
as follows:
[Link] works at client side so less response time.
[Link]
[Link] can be executed by browsers running under
class [Link]
many plateforms, including Linux, Windows, class [Link]
Mac Os etc. class [Link]
Drawback of Applet class [Link]
Plugin is required at client browser to execute class [Link]
applet.
Differentiate between applet and application

Java Application Java Applet


Java Applications are the stand-alone Java Applets are small Java programs
programs which can be executed which are designed to exist within HTML
independently web document
Java Applications must have main() Java Applets do not need main() for
method for them to execute execution
Java Applets cannot run independently
Java Applications just needs the JRE
and require API’s
Java Applications do not need to extend Java Applets must extend
any class unless required [Link] class
Java Applications can execute codes from
Java Applets Applications cannot do so
the local system

Java Applications has access to all the Java Applets has access only to the
resources available in your system browser-specific services
How to run applet code/program
There are, however, two methods of running
an applet.
Type1 Type2
Both java code and applet/html code presents Java code and applet/html code presents separately in
in one program. the program.

Java code Java code


+
Save the program as [Link]
/*
< applet code = "MyApplet" width=400 a)Compile the java program using javac command
height=400 > >javac [Link]
< /applet >
*/ Prepare/Write the applet/html code separately
Save the program as [Link] Save the program as [Link]
a)Compile the java program using javac
command Open internet explorer browser and type the path of
the program where the file is located/saved location
>javac [Link]
b) Run the applet code using appletviewer
command
>appletviewer [Link]
To write the applet code in the program user
has to include the following packages

[Link] [Link].*;
[Link] [Link].*;

Note
[Link] applet classname must be type public.
[Link] programs doesn’t contain main() it
contains paint() for displaying text/ message/
values on the generated applet window.
[Link] the paint method Graphics class used
and object are used.
4. Use [Link] method to display any
message in the mentioned coordinates.
[Link] the applet code write the classname and
mention the height and weight coordinates
//Example of an simple Applet program
Output
import [Link].*;
import [Link].*;
public class app extends Applet
{
public void paint(Graphics g)
{
[Link](“LBRCE", 200, 300);
}
}

/*
< applet code=“app” height=200
width=300>
</applet>
*/

Save is as [Link]
Compile the program using
>javac [Link]

Execute the program using


>appletviewer [Link]
Life cycle of an Applet/Applet Life Cycle
Following are the methods of applet life cycle.
[Link]() method [Link]( ): The init( ) method is the first method
[Link]() method to be called. This is where you should initialize
[Link]() method variables.
[Link]() method Programmer can utilize this method to
[Link]() method instantiate objects, initialize variables, setting
background and foreground colors in GUI etc..
This method is called only once during the run
time of your applet.

[Link]( ): The start() method contains the


actual code of the applet that should run. The
start() method executes immediately after
the init() method.
It also executes whenever the applet is
restored, maximized or moving from one tab to
another tab in the browser.
[Link]( ) : The paint() method is used to
redraw the output on the applet display area. // example program for applet lifecycle
The paint() method executes after the import [Link].*;
execution of start() method and whenever the import [Link].*;
applet or browser is resized. import [Link].*;
public class applifcycle extends Applet
4. stop( ) : The stop() method stops the {
execution of the applet. The stop() method String txt;
public void init()
executes when the applet is minimized or
{
when moving from one tab to another in the setBackground([Link]);
browser. setForeground([Link]);
txt="Inside Init()->";
[Link]( ) : The destroy() method }
executes when the applet window is closed or public void start()
when the tab containing the webpage is {
closed. txt+="Inside Start()->";
}
stop() method executes just before when
public void stop()
destroy() method is invoked. {
The destroy() method removes the applet txt+="Inside Stop()->";
object from memory. }
Output

public void paint(Graphics g)


{
Font f=new Font("Times New
Roman",[Link]+[Link],14);
[Link](f);
txt+="Inside Paint()->";
[Link](txt,50,100);
}
}

/*
<applet code="applifcycle" height=200
width=300>
</applet>
*/
Passing parameters to an applet
getParameter() Method
Parameters specify extra information that can The getParameter() method of the Applet class can
be passed to an applet from the HTML page. be used to retrieve the parameters passed from the
Parameters are specified using the HTML page.
HTML’s param tag.
The syntax of getParameter() method is as follows:
The <param> tag is a sub tag of the
<applet> tag. String getParameter(String param-name)
The <param> tag contains two
attributes: name and value which are used
to specify the name of the parameter and the
value of the parameter respectively.

Example
<param name=”name” value=”Ramesh”/>
<param name=”age” value=”25″ />

Now, these two parameters can be accessed


in the applet program using
the getParameter() method of
the Applet class.
// passing parameters to an applet
import [Link].*; /*
import [Link].*; <applet code="paraapp" width=200 height=300>
import [Link].*; <param name="String" value="RED">
</applet>
public class paraapp extends Applet
*/
{
Output
String str;
public void init()
{
setBackground([Link]);
setForeground([Link]);
str=getParameter("String");
if(str==null)
str= "JAVA";
else
str="HELLO"+ str;
}
public void paint(Graphics g)
{
[Link](str,100,200);
}
}
/*
<applet code="paraapp" width=200 height=300>
<param name=“" value="RED">
</applet>
*/

Output
Warning: <param name=... value=...> tag
requires name attribute.
2. //Drawing a Rectangle
Graphics class in Java [Link](int x,int y,int width,int
height);
The Graphics class provides the framework
x,y-> Coordinates
for all graphics operations within the AWT.
It plays two different, but related, roles. 3. //Filling a Rectangle
First, it is the graphics context. [Link](int x,int y,int width,int
The graphics context is information that will height);
affect drawing operations. 4. //Drawing a Rectangle with Rounded Edges
[Link](int x,int y,int
This includes the background and foreground
height,int width,int xdiamter,int ydiameter);
colors, the font, and the location and
dimensions of the clipping rectangle (the 5.//Filling a Rectangle with Rounded Edges
region of a component in which graphics can [Link](int x,int y,int
be drawn). height,int width,int xdiamter,int ydiameter);

Graphics class methods 6.//Drawing a Oval


[Link](int x,int y,int width,int
1. //Drawing a Line height);
[Link](int x1,int y1,int
x2,int y2); 7.//Filling a Oval
(x1,y1)-> Starting Point [Link](int x,int y,int width,int
height);
(x2,y2)-> Ending Point
8.// Drawing an Arc
//example for graphics class
[Link](int x,int y,int import [Link].*;
height,int width,int startdegress,int import [Link].*;
arcdegress) import [Link].*;
public class graphics extends Applet
{
9.//Filling an Arc
public void paint(Graphics g)
[Link](int x,int y,int {
height,int width,int startdegress,int [Link]([Link]);
arcdegress) [Link](10,50,60,70);
D [Link]([Link]);
[Link](40,30,80,50);
10.//Drawing a Polygon [Link]([Link]);
[Link](int [Link](70,100,110,80);
[Link]([Link]);
xcoordinates,int ycoordinates,int [Link]
[Link](120,100,110,150,140,170);
edges); [Link]([Link]);
[Link](270,190,230,170,160,80);
11.//Filling a Polygon [Link]([Link]);
[Link](int [Link](270,130,150,120,110,180);
xcoordinates,int ycoordinates,int [Link] [Link]([Link]);
edges);
Output

[Link](420,250,330,240,250,160);
int x[]={170,190,100};
int y[]={210,140,120};
[Link](x,y,3);
int x1[]={270,220,100};
int y1[]={240,210,250};
[Link](x1,y1,3);
}
}

/*
<applet code="graphics" height=300
width=200>
</applet>
*/
Event Handling
Event
Change in the state of an object is known as event.
Events are generated as result of user interaction
with the graphical user interface components.
What is Event Handling?
For example, clicking on a button, moving the
Event Handling is the mechanism that controls the
mouse, entering a character through
event and decides what should happen if an event
keyboard,selecting an item from list, scrolling the
occurs.
page are the activities that causes an event to
This mechanism have the code which is known as
happen.
event handler that is executed when an event
Types of Events
occurs.
The events can be broadly classified into two
all the events are available in [Link].* package.
categories:
Foreground Events - Those events ware
ex: Mouseclinking, mouse moving,mouse
generated as consequences of a person interacting
dragging,typing with keyboard,
with the graphical components in Graphical User
interction of the user with system
Interface.
For example, clicking on a button, moving the
Components of Event Handling
mouse, entering a character through
Event handling has three main components,
keyboard,selecting an item from list, scrolling the
Events: An event is a change in state of an object.
page etc.
Events Source: An event source is an object that
Background Events - Those events that require
generates an event.
the interaction of end user are known as
Listeners: A listener is an object that listens to the
background events. Operating system interrupts,
event. A listener gets notified when an event occurs.
hardware or software failure, timer expires, an
operation completion are the example of
background events.
Event Delegation Model
Listener waits until it receives an event.
Java Uses the Delegation Event Model to handle
Once the event is received,the listener process the
the events. event an then returns.
This model defines the standard mechanism to
generate and handle the events. For example, the MouseListener interface deals
with mouse events, and the ActionListener interface
The event delegation model comprises three deals with action events fired by buttons and other
elements: components.
[Link] source
[Link] listener [Link]
[Link] Adapters are abstract classes that implement listener
[Link] Source - The source is an object on interfaces using predefined methods. These are
which event occurs. provided for convenience.
Source is responsible for providing information
of the occurred event to it's handler. Java
provide as with classes for source object.
For example, if a user clicks and drags an icon,
you can sum up the mouse-clicked event and
the mouse-moved event into one event object.
[Link] Listener - It is also known as event
handler.
Listener is responsible for generating response
to an event.
Event Classes
All the events are available in
[Link]
[Link].*; package Abstract super class for all component input event
EventClassName Description classes.
--------------------------------------------------------- [Link]
[Link] Event Generated when a check box or a list item is clicked;
also occurs when a choice selection is made or a
Generated when a button is pressed, a list is checkable menu is selected or deselected.
double-clicked, or a menu item is selected. [Link]
Generated when the mouse is dragged, moved,
[Link] clicked, pressed, or released; also generated when
Generated when a scroll bar is manipulated. the mouse enters or exits a component.
[Link] [Link]
Generated when a component is hidden, Generated when the value of a textarea or textfield is
changed.
moved, resized, or becomes visible.
[Link]
[Link] Generated when a window os activated, closed,
Generated when a component is added to or deactivated, deiconified,iconified, opened, or quit.
removed from a container. [Link]
[Link] It Represents keystrokes/keyboard events
Generated when a component gains or loses
keyboard focus.
event listener interfaces
Event Sources
Interface Meaning
Button : Generates action events when the button ActionListener This interface deals with the
is pressed. action events.
Check box : Generates item events when the AdjustmentListene This interface deals with the
check box is selected or deselected. r adjustment event generated by
Choice : Generates item events when the choice is the scroll bar.
changed. ComponentListene This interface deals with the
List : Generates action events when an item is r component events.
double-clicked; generates item events when an
item is selected or deselected. ContainerListener This interface deals with the
Menu item : Generates action events when a events that can be generated on
containers.
menu item is selected; generates item events
when a checkable menu item is selected or FocusListener This interface deals with focus
deselected. events that can be generated on
Scroll bar : Generates adjustment events when different components or
the scroll bar is manipulated. containers.
Text components : Generates text events when the ItemListener This interface deals with the
user enters a character. item event.
Window : Generates window events when a
KeyListener This interface deals with the key
window is activated, closed, deactivated,
events.
deiconified, iconified, opened, or quit.
MouseListener his interface deals with five of
the mouse events.
Mouse Handling Events
Mouse events are of two types.
MouseListener handles the events when the mouse is not in motion.
While MouseMotionListener handles the events when mouse is in motion.
MouseListener and MouseMotionListener is an interface in [Link] package .
There are five types of events that MouseListener/Interface can generate.

a)MouseClicked
b)MouseEntered
c)MouseExited
d)MousePressed
e)MouseReleased

[Link] mouseReleased(MouseEvent e) : Mouse key is released


[Link] mouseClicked(MouseEvent e) : Mouse key is pressed/released
[Link] mouseExited(MouseEvent e) : Mouse exited the component
[Link] mouseEntered(MouseEvent e) : Mouse entered the component
[Link] mousepressed(MouseEvent e) : Mouse key is pressed

There are two types of events that MouseMotionListener can generate.


a)MouseDragged
b)MouseMoved

1. void mouseDragged(MouseEvent e) : Mouse is dragged


2. void mouseMoved(MouseEvent e): Mouse is moved
//example program using mouseevents
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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;
showStatus("Mouse Clicked");
repaint();
}
public void mouseReleased(MouseEvent me)
public void mouseEntered(MouseEvent me) {
{ mouseX=[Link]();
mouseX=0; mouseY=[Link]();
mouseY=10; showStatus("Mouse Released");
repaint();
showStatus("Mouse Entered"); }
repaint(); public void mouseDragged(MouseEvent me)
} {
mouseX=[Link]();
public void mouseExited(MouseEvent me) mouseY=[Link]();
{ showStatus("Mouse Dragged at" +mouseX+" "+mouseY);
mouseX=0; repaint();
}
mouseY=10;
public void mouseMoved(MouseEvent me)
showStatus("Mouse Exited"); {
repaint(); showStatus("Mouse Moved at"+[Link]()+" "+[Link]());
} repaint();
}
public void mousePressed(MouseEvent me) public void paint(Graphics g)
{ {
mouseX=[Link](); [Link](msg,mouseX,mouseY);
}
mouseY=[Link]();
}
showStatus("Mouse Pressed"); /*
repaint(); <applet code="mouseevents" width=300 height=300>
} </applet>
*/
Keyboard Events/Key Events
To perform keyboard operations/ //example for key events
functionalities. import [Link].*;
To perform keyevents it requires KeyListener import [Link].*;
interface import [Link].*;
import [Link].*;
The operations of the keyevents are public class keyevent extends Applet implements
KeyListener
a)keyPressed
{
b)keyReleased String msg;
c)keyTyped public void init()
{
[Link] keyPressed(KeyEvent ke) : Keyborad addKeyListener(this);
key is Pressed }
public void paint(Graphics g)
[Link] keyReleased(KeyEvent ke) : Keyborad {
[Link](msg,20,50);
key is released
}
public void keyPressed(KeyEvent me)
3. void keyTyped(KeyEvent ke) : Keyborad {
key is Typed msg="key pressed";
repaint();
}
public void keyReleased(KeyEvent me)
{
msg="key Released";
repaint();
}
public void keyTyped(KeyEvent me)
{
msg="key typed";
repaint();
}

}
/*
<applet code="keyevent" width=300
height=300>
</applet>
*/
//example for adapter class
Adapter class import [Link].*;
It is to perform single/unique operation in import [Link].*;
import [Link].*;
either mouse events or key events
import [Link].*;
class key extends KeyAdapter
Here it requires KeyAdapter interface to {
perform any task. public void keyTyped(KeyEvent ke)
{
[Link]("key typed");
syn: public void init() }
{ }
addKeyListener(new key() public class adapter1 extends Applet
{
any operation String msg="LBRCE";
public void init()
) {
} addKeyListener(new key()
{
public void KeyTyped(KeyEvent ke)
{
msg="Key Typed";
showStatus(msg);
repaint();
}
});
}
public void paint(Graphics g)
{
[Link](msg,10,20);
}
}

/*
<applet code="adapter1" width=300
height=300>
</applet>
*/
//Example for inner class
Inner Class //outer class
java inner class or nested class is a class which class Outer
is declared inside the class or interface. {
We use inner classes to logically group classes // Simple nested inner class
and interfaces in one place so that it can be class Inner
more readable and maintainable. {
Additionally, it can access all the members of public void run()
outer class including private data members and {
methods. [Link]("In a nested inner class
method");
Syntax of Inner class }
}
class Java_Outer_class{ }
class innclass
//code
{
class Java_Inner_class{
public static void main(String[] args)
//code
{
} [Link] in = new Outer().new Inner();
} [Link]();
Advantages of java inner classes }
•it can access all the members (data members }
and methods) of outer class including private.
•Code Optimization: It requires less code to Output
write. In a nested inner class method
Anonymous Inner Class
An inner class declared without a class name is //Example for anonymous inner class
known as an anonymous inner class. abstract class Person
In case of anonymous inner classes, we declare {
and instantiate them at the same time. abstract void eat();
Generally, they are used whenever you need to }
override the method of a class or an interface. class aninclass
Syntax of Anonymous Inner class {
public static void main(String args[])
AnonymousInner an_inner = new AnonymousInner() {
{ Person p=new Person()
public void my_method() {
void eat()
{
{
........
[Link]("Example for Anonymous
........
Innerclass");
} }
}; };
[Link]();
}
}
Output
Example for Anonymous Innerclass
THANK YOU

You might also like