[go: up one dir, main page]

0% found this document useful (0 votes)
90 views38 pages

Applet 1

Applet class - All applets must extend the Applet class and import java.applet. Applets are executed by a web browser or applet viewer rather than a runtime interpreter. - The Applet class defines lifecycle methods like init(), start(), stop(), destroy() that are called when the applet loads, runs, pauses, and unloads. It also provides methods for displaying images, audio, and user input. - An applet is event-driven and waits for events like mouse clicks to respond to. The AWT notifies the applet of events by calling event handler methods provided by the applet.
Copyright
© Attribution Non-Commercial (BY-NC)
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)
90 views38 pages

Applet 1

Applet class - All applets must extend the Applet class and import java.applet. Applets are executed by a web browser or applet viewer rather than a runtime interpreter. - The Applet class defines lifecycle methods like init(), start(), stop(), destroy() that are called when the applet loads, runs, pauses, and unloads. It also provides methods for displaying images, audio, and user input. - An applet is event-driven and waits for events like mouse clicks to respond to. The AWT notifies the applet of events by calling event handler methods provided by the applet.
Copyright
© Attribution Non-Commercial (BY-NC)
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
You are on page 1/ 38

Applet class

All applets are subclasses of Applet. Thus, all applets


must import java.applet. Applets must also import
java.awt
It is necessary to include support for that window.
Applets are not executed by the console-based Java run-
time interpreter.
they are executed by either a Web browser or an applet
viewer.
it is handled with various AWT methods, such as
drawString( ), which outputs a string to a specified X,Y.
Once an applet has been compiled, it is included in an HTML
file using the APPLET tag. The applet will be executed by a
Java-enabled web browser when it encounters the APPLET tag
within the HTML file
To view and test an applet more conveniently, simply
include a comment at the head of Java source code
file that contains the APPLET tag.

/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
The Applet Class
The Applet class defines the methods

Applet provides all necessary support for applet


execution, such as starting and stopping. It also
provides methods that load and display images, and
methods that load and play audio clips.
Applet extends the AWT class Panel. In turn, Panel
extends Container, which extends Component.
void destroy( ) :
Called by the browser just before an applet is terminated. Your
applet will override this method if it needs to perform any
cleanup prior to its destruction.
void init( )
Called when an applet begins mexecution. It is the first method
called for any applet.
void start( )
Called by the browser when an applet should start (or resume)
execution. It is automatically called after init( ) when an applet
first begins.
void stop( )
Called by the browser to suspend execution of the applet. Once
stopped, an applet is restarted when the browser calls start( ).
Applet Architecture
An applet is a window-based program
applets are event driven
An applet waits until an event occurs. The AWT
notifies the applet about an event by calling an event
handler that has been provided by the applet
user initiates interaction with an applet
These interactions are sent to the applet as events
to which the applet must respond. For example, when
the user clicks a mouse inside the applet’s window, a
mouse-clicked event is generated.
An Applet Skeleton
Mechanism by which the browser or applet
viewer interfaces to the applet and controls its
execution. Four of these methods—init( ), start( ),
stop( ), and destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT
Component class.
public void start() {
// An Applet skeleton. // start or resume execution
import java.awt.*; }
import java.applet.*; // Called when the applet is stopped.
/*
<applet code="AppletSkel" public void stop() {
width=300 height=100> // suspends execution
</applet> }
*/ /* Called when applet is terminated.
public class AppletSkel extends This is the last
Applet { method executed. */
// Called first. public void destroy() {
public void init() { // perform shutdown activities
// initialization }
// Called when an applet's window
} must be restored.
/* Called second, after init(). Also public void paint(Graphics g) {
called whenever the applet is // redisplay contents of window
restarted. */
}
}
When run, it generates the following window when viewed with an applet
viewer:
Applet Initialization and
Termination
It is important to understand the order in which the various
methods shown in the skeleton are called. 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( )
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 once—the
first time an applet is loaded—start( ) is called each time an applet’s
HTML document is displayed onscreen. So, if a user leaves a web page
and comes back, the applet resumes execution at start( ).
paint( )
The paint( ) method is called each time your applet’s output must be
redrawn. This situation can occur for several reasons. For example, the
window in which the applet is running may be overwritten by another
window and then uncovered. Or 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
appletis required.
stop( )
The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page,
for example. When stop( ) is called, the applet is probably
running. You should use stop( ) to suspend threads that don’t
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( ).
Simple applet program
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
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 Java’s stream I/O
classes. Instead, applets
use the interface provided by the AWT.
import java.awt.*;
import java.applet.*;
/*
<applet code=“Userin" width=300 height=100>
</applet>
*/
public class userin extends Applet {
TextField t1,t2
public void init() {
t1= new TextField(8);
t2= new TextField(8);
Add(t1);
Add(t2);
t1.setText(“0”);
t2.setText(“0”);
}
z= x+y;
public void paint(Graphics g)
s=String.valueOf(z);
{
g.drawString(“The sum is :”,10,75);
Int x=0,y=0,z=0;
g.drawString(s,100,75);
String s1,s2,s;
}
g.drawString(“input number in
each block”,10,50);
Try Public boolean action(Event e,
object o)
{
{
s1 = t1.getText();
repaint();
x=Integer.parseInt(s1);
return true;
s2 = t2.getText();
}
y=Integer.parseInt(s1);
}
}
Catch(Exception e){ }


Overriding update( )
public void update(Graphics g) {
// redisplay your window, here.
}
public void paint(Graphics g) {
update(g);
}
This method is called when your applet has requested
that a portion of its window be redrawn. The default
version of update( ) first fills an applet with the
default background color and then calls paint( ).
Simple Applet Display Methods
To set the background color of an applet’s window, use
setBackground( ). To set the foreground color (the color in which
text is shown, for example), use setForeground( ). These methods
are defined by Component, and they have the following general
forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
Color getBackground( )
Color getForeground( )
setBackground(Color.green);
setForeground(Color.red);
Requesting Repainting
Applet writes to its window only when its update( ) or
paint( ) method is called by the AWT.
Whenever your applet needs to update the information
displayed in its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT.
The repaint( ) method has four forms.
 void repaint( ) : causes the entire window to be
repainted.
 void repaint(int left, int top, int width, int height)
specifies a region that will be repainted
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int
width, int height)
Here, maxDelay specifies the maximum number of
milliseconds that can elapse before update( ) is
called. Beware, though. If the time elapses before
update( ) can be called.
Using the Status Window
In addition to displaying information in its window,
an applet can also output a message to the status
window of the browser or applet viewer on which it is
running.
To do so, call showStatus( ) with the string that you
want displayed.
 The status windowis a good place to give the user
feedback about what is occurring in the applet,
suggest options, or possibly report some types of
errors.
// Using the Status Window.
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);
}
public void paint(Graphics g) {
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}}
The HTML APPLET Tag
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 = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE
CODEBASE is an optional attribute that specifies the base URL
of the applet code, which is the directory that will be searched
for the applet’s executable class file (specified by the CODE tag).
The HTML document’s URL directory is used as the CODEBASE
if this attribute is not specified. The CODEBASE does not have
to be on the host from which the HTML document was read.
CODE
CODE is a required attribute that gives the name of the file
containing your applet’s compiled .class file. This file is relative
to the code base URL of the applet, which is the directory that
the HTML file was in or the directory indicated by CODE BASE
if set.
ALT
The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser understands the
APPLET tag but can’t currently run Java applets. This is distinct
from the alternate HTML you provide for browsers that don’t
support applets.
NAME
NAME is an optional attribute used to specify a name for the applet
instance. Applets must be named in order for other applets on the same
page to find them by name and communicate with them. To obtain an
applet by name, use getApplet( ), which is defined by the AppletContext
interface.
WIDTH AND HEIGHT
WIDTH and HEIGHT are required attributes that give the size (in pixels) of
the applet display area.
ALIGN
ALIGN is an optional attribute that specifies the alignment of the applet.
This attribute is treated the same as the HTML IMG tag with these possible
values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE, and ABSBOTTOM.
VSPACE AND HSPACE
These attributes are optional. VSPACE specifies the space, in pixels, above
and below the applet. HSPACE specifies the space, in pixels, on each side
of the applet. They’re treated the same as the IMG tag’s VSPACE and
HSPACE attributes.
PARAM NAME AND VALUE
The PARAM tag allows you to specify applet specific arguments in an
HTML
A Simple Banner Applet
import java.awt.*;
import java.applet.*;
public void init() {
/*<applet code="SimpleBanner"
width=300 height=50> setBackground(Color.cyan);
</applet>*/ setForeground(Color.red);
public class SimpleBanner }
extends Applet implements // Start thread
Runnable {
String msg = " A Simple Moving
public void start() {
Banner."; t = new Thread(this);
Thread t = null; stopFlag = false;
int state; t.start();
boolean stopFlag; }
public void run() {
char ch;
// Display banner
for( ; ; ) {
try {
// Pause the banner.
repaint(); public void stop() {
Thread.sleep(250);
ch = msg.charAt(0); stopFlag = true;
msg = msg.substring(1,
msg.length()); t = null;
msg += ch; }
if(stopFlag) // Display the banner.
break;
} catch(InterruptedException e) {}
public void paint(Graphics
}}
g) {
g.drawString(msg, 50, 30);
}
}
Passing Parameters to Applets
To retrieve a parameter, use the getParameter( )
method. It returns the value of the specified
parameter in the form of a String object. Thus, for
numeric and boolean values, you will need to convert
their string representations into their internal
formats.
import java.awt.*;
import java.applet.*;
/*<applet code="ParamDemo" fontName = getParameter("fontName");
width=300 height=80> if(fontName == null)
<param name=fontName fontName = "Not Found";
value=Courier> param = getParameter("fontSize");
<param name=fontSize value=14> try {
<param name=leading value=2> if(param != null) // if not found
<param name=accountEnabled fontSize = Integer.parseInt(param);
value=true></applet> */ else
fontSize = 0;
public class ParamDemo extends } catch(NumberFormatException e) {
Applet{ fontSize = -1;
String fontName; }
int fontSize; param = getParameter("leading");
float leading; try {
boolean active;
// Initialize the string to be
displayed.
public void start() {
String param;
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}
getDocumentBase( ) and
getCodeBase( )
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 applet’s class file was loaded (the code
base).
getDocumentBase( ) and getCodeBase( ).
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);
}
}
AppletContext and showDocument( )
To allow your applet to transfer control to another URL, you
must use the showDocument( ) method defined by the
AppletContext interface.
AppletContext is an interface that lets you get information from
the applet’s execution environment.
 The context of the currently executing applet is obtained by a
call to the getAppletContext( ) method defined by Applet.
 Within an applet, once you have obtained the applet’s context,
you can bring another document into view by calling
showDocument( ).
This method has no return value and throws no exception if it
fails, so use it carefully. There are two showDocument( )
methods. The method showDocument(URL) displays the
document at the specified URL.
/* Using an applet context, getCodeBase(), and
showDocument() to display an HTML file. */
import java.awt.*;
import java.applet.*;
import java.net.*;
/*<applet code="ACDemo" width=300 height=50> </applet>*/
public class ACDemo extends Applet{
public void start() {
AppletContext ac = getAppletContext();
URL url = getCodeBase(); // get url of this applet
try {
ac.showDocument(new URL(url+"Test.html"));
} catch(MalformedURLException e) {
showStatus("URL not found");
}}}
The Abstract Methods Defined by
the AppletContext Interface
1. Applet getApplet(String appletName)
 Returns the applet specified by appletName if it is within the current
applet context. Otherwise, null is returned
 Enumeration getApplets( ) Returns an enumeration that contains all of
theapplets within the current applet context..
 AudioClip getAudioClip(URL url) Returns an AudioClip object that
encapsulates the audio clip found at the location specified by url.

 void showDocument(URL url) Brings the document at the URL


specified by url into view. This method may not be supported by applet
viewers.
 void showDocument(URL url, String where) Brings the document at
the URL specified by url into view. This method may not be supported by
applet viewers. The placement of the document is specified by where as
described in the text
The AudioClip Interface
The AudioClip interface defines these methods:
play( ) (play a clip from thebeginning),
stop( ) (stop playing the clip), and
loop( ) (play the loop continuously).
After you have loaded an audio clip using
getAudioClip( ), you can use these methods to play
it.
The AppletStub Interface
The AppletStub interface provides the means by
which an applet and the browser (or applet viewer)
communicate. Your code will not typically implement
this interface
Outputting to the Console
 Although output to an applet’s window must be accomplished
through AWT methods, such as drawString( ), it is still possible to
use console output in your applet—especially for debugging
purposes.
 In an applet, when you call a method such as System.out.println(
), the output is not sent to your applet’s window. Instead,
 it appears either in the console session in which you launched the
applet viewer or in the Java console that is available in some
browsers.
 Use of console output for purposes other than debugging is
discouraged, since it violates the design principles of the graphical
interface most users will expect.

You might also like