0% found this document useful (0 votes)
10 views23 pages

Java Applet Life Cycle

Chapter 4 discusses applets, which are Java programs embedded in web pages that run on the client side, detailing their lifecycle, advantages, and disadvantages. It outlines the applet lifecycle stages and methods, provides examples of creating applets using HTML and appletviewer, and introduces AWT classes and controls such as labels, buttons, checkboxes, and text fields. The chapter also explains event sources, event classes, and listener interfaces that handle user interactions in Java applications.

Uploaded by

soloh.2nd
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)
10 views23 pages

Java Applet Life Cycle

Chapter 4 discusses applets, which are Java programs embedded in web pages that run on the client side, detailing their lifecycle, advantages, and disadvantages. It outlines the applet lifecycle stages and methods, provides examples of creating applets using HTML and appletviewer, and introduces AWT classes and controls such as labels, buttons, checkboxes, and text fields. The chapter also explains event sources, event classes, and listener interfaces that handle user interactions in Java applications.

Uploaded by

soloh.2nd
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/ 23

Chapter– 4

4.1 DefineApplet and Lifecycleof an Applet

Applet:

-> 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 atclientside.

->An Applet is a class contained in the java. applet package. Applet class contains several
methods that give you detailed controlovertheexecution of yourapplet.

->all applets must importjava.applet and alsomustimport java.awtpackage

Advantage of Applet

o It works atclientside soless responsetime.


o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser toexecuteapplet.

Life cycle of an Applet:

The applet life cycle can be defined as the process of how the object is created, started,
stopped,and destroyed during theentireexecution of itsapplication.

Applet lifecycleincludes thefollowing states

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

TheAppletclass provide4 methods


1. init()
2. start()
3. Stop()
4. destroy()
and AWT Component class provide 1 lifecyclemethod
5. paint();

1. public void init():


a. The init() method is the first method to be called. This is where you should
initialize variables. And in this method set Background and Foreground
colours of an applet. This method is called only once during the run time of
your Applet.
2. public void start():
a. The start () method called after the init() or browser is maximized. It is used
to start applet. Example: if a user leaves a web page and comes back, the
applet resumes executionat start

3. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can beused for drawing oval, rectangle,arc,string etc.
4. public void stop(): is used to stop the Applet. It is called when Applet is stop or
browseris minimized.
5. public void destroy(): is used to destroy the Applet i.e applet is removed
completely from thememory. It is called only once.

4.2 Explain the creation of Applets with example programs

In twowayswe can runjava Applets

1. by htmlfile
2. by appletviewer tool

1.Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create
an html file and placetheapplet codein html file. Now clickthehtmlfile.
Example:
APPLET Code:
//saveas appletDemo.javaand compile it

import java.applet.*;
import java.awt.*;
public class appletDemoextends Applet
{
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
}
public void paint(Graphicsg)
{
g.drawString("applet programming",100,100);
}
}
HTML FILE:
//saveas myapplet.html
<html>
<body>
<appletcode="appletDemo" width=100 height=100>
</applet>
</body>
</html>
2. Using appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
commentand compileit. Afterthatrun itby:appletviewer First.java.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

public class First extends Applet


{

public void paint(Graphics g)


{
g.drawString("welcome to applet",150,150);
}

}
Passing Parameters to an applet:
Wecan give user defined parameters toan applet using <PARAM> tag. <PARAM> tag has
two attributes nameattributeand valueattribute.
In the applet code, applet can refers to that parameters by name to find its value. We can
define init() method to get parameters defined in the <PARAM> tag. This is done using
getParameter() method, which takes one string argument representing the name of the
parameter and returnsa string containing thevalue of thatparameter.
Example:
import java.awt.*;
import java.applet.*;
/*<appletcode="Passargument" width=500 height=500 align=right>
<PARAM name="string",value="hi amgoing">
</applet>
*/
public class Passargumentextends Applet
{
String s;
public void init()
{
s=getParameter("string");
}
public void paint(Graphics g)
{
g.drawString(s,50,50);
}
}
4.3 Listand discuss AWT Classes
Java AWT (Abstract Window Toolkit) is
inJava.
The AWT classes are contained in the java.awt package. It is one of Java’ s largest
packages. itis logically organized in a top-down,hierarchical fashion.
Component:
At the top of the AWT hierarchy is Component. Component is an abstract class that
encapsulate all the attributes of visual components. All the user interface elements that
aredisplayed on thescreen and that interact with the user are subclasses of Component.
It defines over a hundred public methods that are responsible for managing events such
as keyboard and mouse inputs,positioning and sizing thewindow,and repainting.

Container:
Container class is a subclass of Component. It has additional methods. A container is
responsible for laying out any components that it contains. It does through the use of
various layout managers.
Panel:
The panel class is a concrete subclass of container. It doesn’ t add any new methods it
simply implements Container. A panel is a window that does not contain a title bar, menu
bar,orborder.
Window:
You won’ tcreateobject directly forwindow. Instead weuseframe.
Frame:
Frame having titlebar, menu bar,and borders.
4.4 DescribeAWT Controls with examples
TheAWT supports thefollowing types of controls
 Labels
 Push buttons
 Check boxes
 Choicelists
 Lists
 Scroll bars
 Textediting
Labels:
A is an object of type Label, and it contains a string, which it displays. Labels are
passive controls that do not support any interaction with the user. Label defines the
following constructors:
Label( )-- creates a blank label.
Label(String )-- creates a labelthatcontains the string specified by .
Label(String , int )-- creates a label that contains the string specified
by using the alignment specified by . The value of must be one of these three
constants: Label.LEFT, Label.RIGHT,or Label.CENTER.
Example:
import java.awt.*;
import java.applet.*;
/*<appletcode="LabelDemo"width=300 height=300>
</applet>
*/
public class LabelDemo extends Applet
{
public void init()
{
Label l1=new Label("one");
Label l2=new Label("two");
Label l3=new Label("three");
add(l1); //add Labels to appletwindow
add(l2);
add(l3);

Push Buttons:
A is a component that contains a label and generates an event when it is
pressed. Push buttons areobjects of type Button.
Button definesthesetwo constructors:
Button( )-- creates an emptybutton.
Button(String )-- creates abuttonthat contains as a label.

Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo"width=250 height=150></applet>
*/
public class ButtonDemoextends Applet implementsActionListener
{
String msg;
public void init()
{
Button b1=new Button("Yes");
Button b2=new Button("No");
Button b3=new Button("undecided");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
String str= ae.getActionCommand();
if(str.equals("Yes"))
{
msg ="You pressed Yes.";
}
elseif(str.equals("No"))
{
msg = "You pressed No.";
}
else
{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,100);
}
}
Check boxes:
A is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not. There is a label associated with each check
box that describes what option the boxrepresents. You change the state of a check box by
clicking on it. Check boxes can be used individually or as part of a group. Check boxes are
objects of the Checkbox class.

Checkbox supports theseconstructors:

Checkbox( ) -- creates a check boxwhoselabel is initially blank. The state of thecheck box
is unchecked.
Checkbox(String ) -- creates a check box whose label is specified by . The state of
thecheck box is unchecked.
Checkbox(String , boolean )— Creates a checkbox and set the initial state of the
checkbox. If onis true,thecheckbox isinitially checked;otherwise,it is cleared

Checkbox(String ,boolean , CheckboxGroup )


Checkbox(String ,CheckboxGroup ,boolean )
The fourth and fifth forms create a check box whose label is specified by and whose
group is specified by . If this check box is not part of a group, then must
be null.
Examples:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo"width=240 height=200></applet>
*/
public class CheckboxDemoextends Applet implementsItemListener
{
String msg;
Checkboxcb1,cb2,cb3;
public void init()
{
cb1=new Checkbox("C");
cb2=new Checkbox("C++");
cb3=new Checkbox("JAVA");
add(cb1);
add(cb2);
add(cb3);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}
public void itemStateChanged(ItemEventie)
{
repaint();
}
public void paint(Graphics g)
{
msg = "Current state:";
g.drawString(msg,6,80);
msg=" C: "+cb1.getState();
g.drawString(msg,6,100);
msg=" C++:" +cb2.getState();
g.drawString(msg,6,120);
msg=" JAVA: "+ cb3.getState();
g.drawString(msg,6,140);
}
}
Choice:
The Choice class is used to create a of items from which the user may choose.
Thus, a Choice control is a form of menu. When inactive, a Choice component takes up
only enough space to show the currently selected item. When the user clicks on it, the
whole list of choices pops up, and a new selection can be made. Each item in the list is a
string that appearsas a left-justified label in the orderit is added tothe Choice object.
Choice defines only thedefaultconstructor,which creates an empty list.
Toadd a selection to the list,call add( ).

It has this general form:

void add(String )

Here, is the name of the item being added. Items are added to the list in the order in
which calls to add( ) occur.

Example:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo"width=300 height=180></applet>
*/

public class ChoiceDemoextends Applet implements ItemListener


{
Choiceos;
String msg;
public void init()
{
os = newChoice();
os.add("Windows"); //add items toos list
os.add("Android");
os.add("Solaris");
os.add("Mac OS");
add(os); //add choiceliststowindows
os.addItemListener(this); //registertoreceiveitemevents

}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g) // Display current selections.
{

msg = "CurrentOS: ";


msg += os.getSelectedItem();
g.drawString(msg,6,120);

}
}
TextField:
Thetextfield class implements a singleline text entry area,usually called an editcontrol.
TextFields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys and
mouseselections. textField is a subclass of TextComponent. TextField defines the following constructo
TextField()----creates a defaulttextfield
TextField(intnumChars)----creates a text field thatis numCharscharacters wide.
TextField(String str)----initializes thetextfield with thestring contained in str.
TextField(String str,intnumChars)----initializes a textfield and sets its width.

Toobtainthestring currently contained in thetextfield,call getText( ).


Toobtainthecurrently selected text by calling getSeectedText( ).
You can disable the echoing of characters as they are typed by calling setEchoChar( ).

Example:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<appletcode="Text" width=500 height=500>
</applet>*/
public class Textextends Applet implements ActionListener
{
String msg;
TextField name,pass;
public void init()
{
Label l1=newLabel("EnterName",Label.RIGHT);
Label l2=newLabel("EnterPassword",Label.RIGHT);
name=new TextField(10);
pass=newTextField(6);
pass.setEchoChar('*');
add(l1);
add(name);
add(l2);
add(pass);
name.addActionListener(this);
pass.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Name:"+name.getText(),6,50);
g.drawString("Password:"+pass.getText(),6,70);
}
}

Scrollbars:
are used to select continuous values between a specified minimum and
maximum. Scroll barsmaybeorientedhorizontallyorvertically.
Ascrollbaris actually a compositeof several individual parts. Eachend has an arrowthat
you can click to move the current value of the scroll bar one unit in the direction of the
arrow.
Scrollbar defines thefollowing constructors:
Scrollbar()---creates a vertical scroll bar.
Scrollbar(int style)---If is Scrollbar.VERTICAL, a vertical scroll bar is created.
If is Scrollbar.HORIZONTAL,thescrollbaris horizontal.
Scrollbar(int , int , int , int , int )--- the initial
value of the scroll bar is passed in . The number of units represented by the
height of the thumb is passed in . The minimum and maximum values for the
scroll bar arespecified by and .
4.6 Explain Sources of an Events

Source isan object thatgenerates an events. Following aretheSources togenerate


Events.

4.7 Event Classes and Even Listener Interfaces

EventClasses:
EventListener Interfaces:

The ActionListener Interface

This interface defines the actionPerformed( ) method that is invoked when an action
event occurs. Its general formis shown here:

void actionPerformed(ActionEvent )

The AdjustmentListener Interface

This interface defines the adjustmentValueChanged( ) method that is invoked when an


adjustment event occurs. Its general formis shown here:

void adjustmentValueChanged(AdjustmentEvent )

The ComponentListener Interface

This interfacedefines fourmethods that areinvoked when acomponent isresized,moved,


shown,orhidden. Theirgeneral forms are shown here:
void componentResized(ComponentEvent )
void componentMoved(ComponentEvent )
void componentShown(ComponentEvent )
void componentHidden(ComponentEvent )

The ContainerListener Interface

This interface contains two methods. When a component is added to a


container, componentAdded( ) is invoked. When a component is removed from a
container, componentRemoved( ) is invoked. Theirgeneral forms are shown here:

void componentAdded(ContainerEvent )
void componentRemoved(ContainerEvent )

The FocusListener Interface

This interface defines two methods. When a component obtains keyboard


focus, focusGained( ) is invoked. When a component loses keyboard
focus, focusLost( ) is called. Their general formsareshownhere:

void focusGained(FocusEvent )
void focusLost(FocusEvent )

The ItemListener Interface

This interface defines the itemStateChanged( ) method that is invoked when the state of
an itemchanges. Itsgeneral form is shown here:

void itemStateChanged(ItemEvent )

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 acharacter hasbeen entered.

Thegeneral forms of these methods areshown here:


void keyPressed(KeyEvent )
void keyReleased(KeyEvent )
void keyTyped(KeyEvent )
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.
Thegeneral forms of these methods areshown here:

void mouseClicked(MouseEvent )
void mouseEntered(MouseEvent )
void mouseExited(MouseEvent )
void mousePressed(MouseEvent )
void mouseReleased(MouseEvent )

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
themouseis moved. Theirgeneral forms are shown here:

void mouseDragged(MouseEvent )
void mouseMoved(MouseEvent )

The MouseWheelListener Interface

This interface defines the mouseWheelMoved( ) method that is invoked when the mouse
wheelis moved. Itsgeneral form isshownhere:

void mouseWheelMoved(MouseWheelEvent )

The TextListener Interface

This interface defines the textValueChanged( ) method that is invoked when a change
occurs in atext area or text field. Its general form isshownhere:

void textValueChanged(TextEvent )
The WindowFocusListener Interface

This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ).


These are called when a window gains or loses input focus. Their general forms are shown
here:
void windowGainedFocus(WindowEvent )
void windowLostFocus(WindowEvent )

The WindowListener Interface

This interface defines seven methods.


The windowActivated( ) and windowDeactivated( ) methods are invoked when a window
is activated or deactivated, respectively. If a window is iconified,
the windowIconified( ) method is called. When awindowis deiconified,
the windowDeiconified( ) method is called. When a window is opened or closed,
the windowOpened( ) or windowClosed( ) methods are called, respectively.
The windowClosing( ) method is called when a windowis being closed. The generalforms
of thesemethodsare

void windowActivated(WindowEvent )
void windowClosed(WindowEvent )
void windowClosing(WindowEvent )
void windowDeactivated(WindowEvent )
void windowDeiconified(WindowEvent )
void windowIconified(WindowEvent )
void windowOpened(WindowEvent )

4.8 Explain Mouse and Keyboard Events

MouseEvents:

To handle mouse events we must implement MouseListener and MouseMotionListener


interfaces.

Following arethevarious mouse events

MOUSE DRAGGED: Dragged Mouse

MOUSE CLICKED:Clicked Mouse


MOUSE ENTERED: Mouseentered a component

MOUSE EXITED:Mouseexited from a component

MOUSE MOVED: Mousemoved

MOUSE WHEEL:Mousewheelmoved

MOUSE PRESSED: Mousepressed


MOUSE RELEASED: Mousereleased

Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse"width=300 height=180></applet>
*/
public class Mouseextends Applet implementsMouseListener,MouseMotionListener
{
String msg;
int x,y;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEventme)
{
x=10;
y=20;
msg="mouseclicked";
repaint();
}
public void mouseEntered(MouseEventme)
{
x=10;
y=20;
msg="mouseentered";
repaint();
}
public void mouseExited(MouseEventme)
{
x=10;
y=20;
msg="mouseexited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
Graphics g=getGraphics();
g.setColor(Color.red);
g.drawLine(x,y,5,5);
showStatus("dragging mouseat:"+x+","+y);
}
public void mouseMoved(MouseEventme)
{
showStatus("moving mouse at:"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Key Events:
Tohandle keyboard events youmust implementKeyListener interface.
It has the following events
KEY PRESSED: Generated when a key is pressed
KEY RELEASED: Generated whenthekey is released
KEY TYPED:Generated by thekeystroke
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key"width=300 height=180></applet>
*/
public class Key extends Applet implements KeyListener
{
String msg;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("key pressed");
}
public void keyReleased(KeyEventk)
{
showStatus("key released");
}
public void keyTyped(KeyEventk)
{
msg=msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,40);
}
}

4.5 Explain Event handling with Delegation event model


The event which is occurred in the source is handled by using Listener interface is called
event handling.
Source:

Source isan object thatis generates an event.


Examples: Button, checkbox, choiceetc. Arethesources.
Theinitial stateof thecheckbox is unchecked, when we click onit the stateof checkbox is
changed to checked.

Listener:
Listener is an object that is notified when an event is occurs. It receives notification from
thesourcetoprocess an event.

Eventclasses:
Event classes that representsan events.

Theabovedefined things areused tohandleevents.


Delegation event model:
The modern approach to handling an events is delegation event model. Which defines
standard and consistent mechanismtoprocess events.

1. Asourcegenerates an event and sends ittooneormorelisteners.


2. The listener waits until it receives an event. Once received, the listener
processes theevent and then returns.
In the delegation event model, listeners must register with a source in order to receive an
event notification.

Thegeneral form to register listenerswithsourceis


Public void addType(TypeListenetel)

Here, Typeis thenameof theeventand el isa referencetotheevent listener.


Example:
Themethod that registers a keyboard eventlistener is called addkeyListener().
here,each typeof event has its own registration method
implement EventListenermethods toreceive and process these notifications.

You might also like