You are on page 1of 28

APPLET NOTES FOR ECE605

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

INTRODUCTION
 applets are small applications that are accessed on an Internet

server, transported over the Internet, automatically installed,


and run as part of a Web document.
 After an applet arrives on the client, it has limited

access to resources, so that it can produce an arbitrary


multimedia user interface and run complex computations
without introducing the risk of viruses or breaching data
integrity.
2

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Few important points


 Applets do not need a main( ) method.
 Applets must be run under an applet viewer or a Java-

compatible browser.
 User I/O is not accomplished with Javas stream I/O classes.
Instead, applets use the interface provided by the AWT.

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

SIMPLE APPLET
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

IMPORT
This applet begins with two import statements. The first imports the Abstract Window
Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the
console-based I/O classes. The AWT contains support for a window-based, graphical
interface.
The second import statement imports the applet package, which contains the class
Applet.
Every applet that you create must be a subclass of Applet.

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

paint()
The paint( ) method has one parameter of type Graphics. This parameter
contains the graphics context, which describes the graphics environment in
which the applet is running.
This context is used whenever output to the applet is required.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics
class.
This method outputs a string beginning at the specified X,Y location. It has the
following general form: void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window,
the upper-left corner is location 0,0.
The call to drawString( ) in the applet causes the message A Simple
Applet to be displayed beginning at location 20,20.

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Life Cycle of an Applet


 When an applet begins, the AWT calls the following

methods, in this sequence:


1. init( )
2. start( )
3. paint( )
 When an applet is terminated, the following sequence of
method calls takes place:
1. stop( )
2. destroy( )
This methods belong to Applet class.
7

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Details-1
 init( )

The init( ) method is the first method to be called. This is where


you should initialize variables. This method is called only once during
the run time of your applet.
 start( )
The start( ) method is called after init( ). It is also called to
restart an applet after it has been stopped. Whereas init( ) is called
oncethe first time an applet is loadedstart( ) is called each
time an applets HTML document is displayed onscreen. So, if a user
leaves a web page and comes back, the applet resumes execution at start(
).

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Details-2
 paint( )

The paint( ) method is called each time your applets


output must be redrawn.
This situation can occur for several reasons. For example, the applet
window may be minimized and then restored. paint( ) is also
called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output,paint( ) is called.
 The paint( ) method has one parameter of type Graphics.
This parameter will contain the graphics context, which describes
the graphics environment in which the applet is running. This
context is used whenever output to the applet is required.
9

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Details-3
 stop( )

The stop( ) method is called when a web browser leaves the


HTML document containing the appletwhen it goes to
another page, for example. When stop( ) is called, the applet is
probably running.You should use stop( ) to suspend threads
that dont need to run when the applet is not visible.You can
restart them when start( ) is called if the user returns to the
page.
 destroy( )
The destroy( ) method is called when the environment
determines that your applet needs to be removed completely
from memory. At this point, you should free up any resources the
applet may be using. The stop( ) method is always called
before destroy( ).
10

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

showStatus()
// Using the StatusWindow.
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet{
public void init() {
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

11

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

HTML Applet tag


The APPLET tag is used to start an applet from both an HTML document and from an applet viewer.
The syntax for the standard APPLET tag is shown here. Bracketed items
are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeNameVALUE = AttributeValue>]
[< PARAM NAME = AttributeName2VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>

12

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Parameter passing
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
</applet>
*/

13

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Contd..
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {

if(param != null) // if not found


fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
}
// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0,
10);
g.drawString("Font size: " + fontSize, 0, 26);
}
}

14

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

getDocumentBase(),getCodeBase()
Often, you will create applets that will need to explicitly load
media and text. Java will allow the applet to load data from the
directory holding the HTML file that started the applet (the
document base) and the directory from which the applets class file was
loaded (the code base).
These directories are returned as URL objects by
getDocumentBase( ) and getCodeBase( ).

15

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Example..
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/
public class Bases extends Applet{
// Display code and document bases.
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}
16

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Event Model
 applets are event-driven programs. Thus, event handling

is at the core of successful applet programming.


 Most events to which your applet will respond are generated
by the user.
These events are passed to your applet in a variety of ways, with the
specific method depending upon the actual event. There are
Several types of events.
 The most commonly handled events are those generated by the
mouse,the keyboard, and various controls, such as a push button.
Events are supported by the java.awt.event package.
17

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

The Delegation Event Model


 This defines standard and consistent mechanisms to generate and







18

process events. Its concept is quite simple: a source generates an event


and sends it to one or more listeners.
In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that
processes events is cleanly separated from the user interface logic
that generates those events.
A user interface element is able to delegate the processing of an
event to a separate piece of code.
In the delegation event model, listeners must register with a
source in order to receive an event notification. This provides an
important benefit: notifications are sent only to listeners that want
to receive them.

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Events
 Events
 In the delegation model, an event is an object that describes a

state change in a source.


 It can be generated as a consequence of a person interacting
with the elements in a graphical user interface. Some of the
activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an
item in a list, and clicking the mouse.

19

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Event Sources
 Event Sources
 A source is an object that generates an event.This occurs when the internal state of

that object changes in some way. Sources may generate more than one type of
event.
 A source must register listeners in order for the listeners to receive
notifications about a specific type of event. Each type of event has its own
registration method.
 Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called
addMouseMotionListener( ).

20

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class context3 extends Applet
{
Button b1,b2,b3;
String s1="";
String s2="";
public void init()
{ b1=new Button("go");
b2=new Button("back");
b3=new Button("refresh");
b1.addActionListener(new But1());
b2.addActionListener(new But2());
b3.addActionListener(new But3());
setBackground(Color.yellow);//NOTE
}
public void start()
{
add(b1);
add(b2);
add(b3);
}

21

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

public void paint(Graphics g)

class But2 implements ActionListener

{ g.setColor(Color.blue);//NOTE

{ public void actionPerformed(ActionEvent e2)


{ s1="STATUS: BACK BUTTON IS PRESSED";

Font f=new Font("Verdana",Font.ITALIC,40);//NOTE


g.setFont(f);

s2="MESSAGE: BACK BUTTON IS PRESSED";

showStatus(s1);

setBackground(Color.red);

g.drawString(s2,10,200);

repaint();

}
}
class But3 implements ActionListener

class But1 implements ActionListener

{ public void actionPerformed(ActionEvent e3)

{ public void actionPerformed(ActionEvent e1)

{ s1="";

{ s1="STATUS: GO BUTTON IS PRESSED";

s2="";

s2="MESSAGE: GO BUTTON IS PRESSED";

setBackground(Color.yellow);

setBackground(Color.green);//NOTE

repaint();

repaint();

}
}//class
/*<applet code=context3.class height=500 width=850>
</applet>
*/

22

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

// Demonstrate the mouse event handlers.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300
height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of
mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}

23

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.

24

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

public void mousePressed(MouseEvent me) {


// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
} // Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

25

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

26

// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250
height=150>
</applet>
*/
public class ButtonDemo extends Applet implements
ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
SAFE- Saraswati Academy
For Excellence,Kolkata-131.
www.SafeSuccess.blogspot.in
}

public void actionPerformed(ActionEvent ae) {


String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}

27

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

Layout Manager a few points


All of the components that we have shown so far have been positioned by the default
layout manager.
A layout manager automatically arranges your controls within a window by using some type of algorithm.
If you have programmed for other GUI environments, such as Windows, then you are
accustomed to laying out your controls by hand. While it is possible to lay out Java
controls by hand, too, you generally wont want to, for two main reasons.
First, it is very tedious to manually lay out a large number of components. Second, sometimes the width
and height information is not yet available when you need to arrange some control, because
the native toolkit components havent been realized. This is a chicken-and-egg situation;
it is pretty confusing to figure out when it is okay to use the size of a given component to
position it relative to another.
Each Container object has a layout manager associated with it. A layout manager
is an instance of any class that implements the LayoutManager interface. The layout
manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the
default layout manager is used. Whenever a container is resized (or sized for the first
time), the layout manager is used to position each of the components within it.
The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)

28

SAFE- Saraswati Academy For Excellence,Kolkata-131.


www.SafeSuccess.blogspot.in

You might also like