Sunteți pe pagina 1din 151

Applet

An applet is a small Internet-based


program
written
in
Java,
a
programming language for the Web,
which can be downloaded by any
computer.
The applet is usually embedded in an
HTML page on a Web site and can be
executed from within a browser.
The browser must be Java Savvy (i.e.
enabled with JVM).

Steps to create an applet


Step 1: Define an applet class (say MyApplet)
class MyApplet extends java.applet.Applet
{
// code
}

Save the file with a name: MyApplet.java

Compile this file


javac MyApplet.java

A new file i.e. MyApplet.class will be generated


(byte code)

Step 2: Create an HTML file (say


MyApplet.html) and embed the .class file
inside the APPLET tag.
<HTML>
<HEAD>
<TITLE>Welcome Java Applet</TITLE>
</HEAD>
<BODY>
<APPLET
code = MyApplet.class"
width = 500
height = 300 >
</APPLET>
</BODY>
</HTML>

Step 3: Run the applet


appletviewer MyApplet.html
or
Open the MyApplet.html file in Java
savvy browser.

Applets
To design an applet, an Applet class has to be inherited.
To use the Applet class, one needs to import following two
packages:
import java.applet ;
import java.awt ;

Why we need awt package for applet programming?


Since all the applets run in a window, it is necessary to
include support for this package.
Applets are not executed by the console-based Java runtime interpreter. Rather, they are executed by either a Web
browser or an appletviewer (provided by JDK).
Execution of an applet does not begin at main().
Output to your applets window is not performed by
System.out.println(). Rather, it is handled with various AWT
methods, such as drawString(), which outputs a string to a
specified X, Y location.
Input is also handled differently than in an application.

Cont.
Once an applet has been compiled, it (the byte
code with .class file) 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 that HTML file.
<applet
code = class filename
width = pixels
height = pixels>
</applet>

An Applet Skeleton

import java.awt.*;
import java.applet.* ;
public class AppletSample extends Applet
{
public void init() // Called First
{
// Initialization
}
public void start() // Called second, after init()
{ // Starts or resumes execution } // Also called whenever

the applet

is restarted

public void paint(Graphics g)


{ // Displays the contents of a window }
public void stop()
{ // Suspends the execution }
public void destroy() // Called when an applet is terminated
{ // Performs shut down activities }
}
}

Execution of an applet

A Minimized Applet window

start

Life
Cycle of
an
Applet

init()
start()
paint()
No

Applet
disabled
?
Yes

stop()
Applet
enabled
?
No

destroy()
stop

Yes

Applet initialization and termination


When an applet begins, the AWT calls the
methods
following methods, in the sequence as given
below:
1. init()
2. start()
3. paint()
When an applet is terminated, the following
sequence of methods calls takes place:
1. stop()
2. destroy()

Cont.
init()
This is the first methods to be called. This is
where you should initialize variables. This
methods is called only once during the
execution of an applet.

start()
This method is called after init().
It is also called to restart the applet after it
has been stopped.
Whereas init() is called once-the first time an
applet is loaded, start() is invoked each time
an applets HTML document is displayed on
the screen.
So, if a user leaves a web page and comes

Cont.

paint()
paint() is invoked when the execution of an
applet begins.
The paint() method is also called, if an applets
output has to be drawn again. This situation can
occur for several reasons.
For example:
The window in which the applet is running may be
covered by
another window and then uncovered later.
The applet window may be minimized and then
restored.

The paint() method has one parameter of type

Cont.
stop()
The stop() method is called when a web
browser
leaves
the
HTML
document
containing the applet (for example, when it
goes to another page).
You should use stop() to suspend threads that
dont need to be 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.

Applets display method


void drawString(String message, int x, int y)
where
message is a string to be displayed at (x, y) pixel
position.
In a java window, the upper-left corner is location
(0, 0).
The drawString() method does not recognize
newline characters. If you want to start a line of text
on another line, you must do so manually,
specifying the precise (x, y) location where you
want the line to begin.

Cont.
setBackground()
To set the background color of an applets
window.

setForeground()
To set the foreground color e.g. the text.
Syntax:
void
newColor);
void
newColor);

setBackground(Color
setBackground(Color

A simple applet that sets the foreground and


background color and outputs a string
import java.awt.*;
import java.applet.* ;
public class Sample extends Applet
{
String msg;
// set the foreground and background colors
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = new String(Inside init() ) ;
}
// Initialize the string to be displayed.
public void start()
{
msg += Inside start() ;
}

Cont. public void stop()


{
msg += Inside stop() ;
}
// Display msg in applet window

public void paint(Graphics g)


{
msg += Inside paint() ;
g.drawString(msg, 10, 30);
}
} // End of the class

Output1: Effect of squeezing and


expanding an applet window

Example 2: Effect of minimizing and then restoring


an applet window

Graphics, Fonts, and


Color

The Java Graphic Coordinate System

Lines

To draw straight lines, use the drawLine(x1,y1,x2,y2)


method.
drawLine() takes four arguments: the x1 and y1
coordinates of the starting point and the x2 and y2
coordinates of the ending point.
Eg.
public void paint (Graphics g)
{
g.drawLine(25,25,75,75);
}

Rectangles
The Java graphics primitives provide not just one, but three
kinds of rectangles:
Plain rectangles
Rounded rectangles
Three-dimensional rectangles, which are drawn with a shaded
border

For each of these rectangles, you have two methods to


choose from: one that draws the rectangle in outline form,
and one that draws the rectangle filled with color.
To draw a plain rectangle, use either the drawRect() or
fillRect() methods.
Both methods take four arguments: the x and y coordinates
of the top left corner of the rectangle, and the width and
height of the rectangle to draw.
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);

Example: The following paint() method draws two squares:


the left one is a plain and the right one is filled.
public void paint(Graphics g)
{
g.drawRect(20,20,60,60);
g.fillRect(120,20,60,60);
}
(0,

0)

y=20

height=60

x=20

width=60

Rounded Rectangles:
void drawRoundRect ( distance along x-axis from origin,
distance along y-axis from origin,
width,
height,
angle along horizontalplane,
angle along vertical plane ) ;

Rounded Rectangle
public void paint(Graphics g)
{
g.drawRoundRect(20,20,60,60,10,10);
g.fillRoundRect(120,20,60,60,20,20);
}

Three-dimensional rectangles:
public void paint(Graphics g)
{
g.draw3DRect(20,20,60,60,true);
g.draw3DRect(120,20,60,60,false);
}
// The fifth argument is a boolean indicating whether the 3D effect
is to raise
// the rectangle (true) or indent it (false).

Polygons
To draw a polygon you need
a set of x and y coordinates
the drawing method then starts from one, draws a
line to the second, then a line to the third, and so on.

There are two ways to indicate the list of


coordinates:
Using two arrays of xs and ys
Using an instance of Polygon class

Using the first


Using the first
method

method, the drawPolygon()


and
fillPolygon()
methods
take
three
arguments:
An array of integers representing x coordinates
An array of integers representing y coordinates
An integer for the total number of points

The x and y arrays should, of course, have


the same number of elements.
Note that Java does not automatically close
the polygon; if you want to complete the
shape, you have to include the starting point
of the polygon at the end of the array.

Heres an example of drawing a polygons


outline by using first method
public void paint (Graphics g)
{
int x[ ] = { 39,94,97,142,53,58,26 };
int y[ ] = { 33,74,36,70,108,80,106 };
int pts = x.length;
g.drawPolygon(x, y, pts);
}

The second way: by defining an object of


Polygon
class
The second way of calling drawPolygon()

and

fillPolygon() is to use a Polygon object.


The Polygon class is useful if you intend to add points to
the polygon or if youre building the polygon on the fly.
The Polygon class enables you to treat the polygon as
an object rather than having to deal with individual
arrays.
To create a polygon object you can either create an
empty polygon:
Polygon poly = new Polygon();
or create a polygon from a set of points using integer
arrays, as in the previous example:

Cont.

int x[ ] = { 39,94,97,142,53,58,26 };
int y[ ] = { 33,74,36,70,108,80,106 };
int pts = x.length;
Polygon poly = new Polygon(x, y, pts);

Once you have a polygon object, you can append


points to the polygon as you need to:
poly.addPoint(20, 35);
Then, to draw the polygon, just use the polygon
object as an argument to drawPolygon() or
fillPolygon().
Heres that previous example, rewritten this time
with a Polygon object. Youll also fill this polygon
rather than just drawing its outline

Cont.
public void paint(Graphics g)
{
int x[ ] = { 39,94,97,142,53,58,26 };
int y[ ] = { 33,74,36,70,108,80,106 };
int pts = x.length;
Polygon poly = new Polygon(x, y, pts);
g.fillPolygon(poly);
}

Ovals

The drawOval() method draws an outline of


an oval.
The fillOval() method draws a filled oval.
public void paint(Graphics g)
{
g.drawOval(20,20,60,60);
g.fillOval(120,20,100,60);
}

Arc

An arc is a part of an oval.


in fact, the easiest way to think of an arc is as a
section of a complete oval.
The drawArc() method takes six arguments: the
starting corner, the width and height, the angle at
which to start the arc, and the degrees to draw it
before stopping.
Once again, there is a drawArc() method to draw the
arcs outline and the fillArc() to fill the arc.
Filled arcs are drawn as if they were sections of a pie;
instead of joining the two endpoints, both endpoints
are joined to the center of the circle.

Cont.
To construct the method to
draw this arc, the first
thing you do is think of it
as a complete circle.
Then you find the x and y
coordinates and the width
and height of that circle.
Those four values are the
first four arguments to the
drawArc()
or
fillArc()
methods.

Cont.

To get the last two arguments,


think in degrees around the circle.

Zero degrees is at 3 oclock, 90


degrees is at 12 oclock, 180 at 9
oclock, and 270 at 6 oclock.
The start of the arc is the degree
value of the start of the arc.
In this example, the starting point
is the top of the C at 90 degrees.
Therefore,
argument.

90

is

the

fifth

Cont.
The sixth and last argument is
another degree value indicating
how far around the circle to sweep
and the direction to go in (its not
the ending degree angle, as you
might think).
In this case, because youre going
halfway around the circle, youre
sweeping 180 degrees and 180 is
therefore the last argument in the
arc.
The important part is that youre
sweeping
180
degrees
counterclockwise, which is in the
positive direction in Java.
If you are drawing a backwards C,
you sweep 180 degrees in the
negative direction, and the last

Cont.
public void paint(Graphics g)
{
g.drawArc(20,20,60,60,90,180);
g.fillArc(120,20,60,60,90,180);
}

An elliptical arc
Like the arc on the circle, this arc is a piece
of a complete oval, in this case, an elliptical
oval.
By completing the oval that this arc is a part
of, you can get the starting points and the
width and height arguments for the drawArc
or fillArc method

This arc doesnt start on a nice


boundary such as 90 or 180 degrees,
so youll need some trial and error.
This arc starts somewhere around 25
degrees, and then sweeps clockwise
about 130 degrees

A simple graphics example to draw a lamp shade with a


import
base
andjava.awt.*;
a stand
public class Lamp extends java.applet.Applet
{
public void paint(Graphics g)
{
// the lamp platform
g.fillRect(0,250,290,290);
// the base of the lamp
g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);
// the lamp shade, top and bottom edges
g.drawArc(85,157,130,50,-65,312);
g.drawArc(85,87,130,50,62,58);
// lamp shade, sides
g.drawLine(85,177,119,89);
g.drawLine(215,177,181,89);
// dots on the shade
g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
}
}

// lamp shade, sides


g.drawLine(85,177,119,89);
g.drawLine(215,177,181,89);

// dots on the shade


g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
// the lamp shade, top and bottom edges
g.drawArc(85,87,130,50,62,58);
g.drawArc(85,157,130,50,-65,312);

// the base of the lamp


g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);

g.fillRect(0,250,290,290);

Text and Fonts

The Graphics class also enables you to


print text on the screen, in conjunction
with the Font class, and sometimes the
Font metrics class.
The Font class represents a given font
its name, style, and point size.
Font metrics gives you information
about that font (for example, the actual
height or width of a given character) so
that you can precisely layout text in
your applet.

Cont.
Font names are strings representing
the family of the font, for example,
TimesRoman,
Courier,
or
Helvetica.
Font styles are constants defined by
the Font class; you can get to them
using class variablesfor example,
Font.PLAIN, Font.BOLD, or Font.ITALIC.
Finally, the point size is the size of the
font, as defined by the font itself; the
point size may or may not be the
height of the characters.

Cont.
To create an individual font object, use
these three arguments to the Font classs
new constructor:
Font f = new Font(TimesRoman,
Font.BOLD, 24);
This example creates a font object for the
TimesRoman BOLD font, in 24 points.
Font styles are actually integer constants
that can be added to create combined
styles;
for
example,
Font.BOLD
+
Font.ITALIC produces a font that is both
bold and italic.
If Java cant find a font you want to use, it

Drawing Strings
With a font object in hand, you can draw
text on the screen using the method
drawString().
You need to set the current font to your font
object using the setFont() method.
public void paint(Graphics g)
{
Font f = new Font(TimesRoman,
Font.PLAIN,72);
g.setFont(f);
g.drawString(This is a big font,10, 100);
}

This program shows an applet that draws several lines of


text in different fonts
import java.awt.Font;
import java.awt.Graphics;
public class ManyFonts extends java.applet.Applet
{
public void paint(Graphics g)
{
Font f = new Font(TimesRoman, Font.PLAIN, 18);
Font fb = new Font(TimesRoman, Font.BOLD, 18);
Font fi = new Font(TimesRoman, Font.ITALIC, 18);
Font fbi = new Font(TimesRoman, Font.BOLD + Font.ITALIC, 18)
g.setFont(f);
g.drawString(This is a plain font, 10, 25);
g.setFont(fb);
g.drawString(This is a bold font, 10, 50);
g.setFont(fi);
g.drawString(This is an italic font, 10, 75);
g.setFont(fbi);
g.drawString(This is a bold italic font, 10, 100);
}
}

Finding Out Information About a Font


Method

Class

Function

getFont()

Graphic
s

Returns the current font


previously set by setFont()

object

getName( Font
)

Returns the name of the font as a string

getSize()

Returns the current font size (an integer)

Font

as

getStyle() Font

Returns the current style of the font (styles


are integer constants: 0 is plain, 1 is bold,
2 is italic, 3 is bold italic)

isPlain()

Font

Returns true or false if the fonts style is


plain

isBold()

Font

Returns true or false if the fonts style is


bold

isItalic()

Font

Returns true or false if the fonts style is


italic

Font class
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class HelloAgainApplet extends
java.applet.Applet
{
Font f ;
public void init()
{
f= new Font(TimesRoman,Font.BOLD,36);
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString(Hello again!, 5, 50);
}

Using Objects of Color class


Color Name

RGB Value

Color.white

255,255,255

Color.black

0,0,0

Color.lightGray 192,192,192
Color.gray

128,128,128

Color.darkGray 64,64,64
Color.red

255,0,0

Color.green

0,255,0

Color.blue

0,0,255

Color.yellow

255,255,0

Color.magenta

255,0,255

Color.cyan

0,255,255

Color.pink

255,175,175

Color.orange

255,200,0

Cont.
If the color you want to draw in is not one of the standard
color objects, fear not. You can create a color object for
any combination of red, green, and blue, as long as you
have the values of the color you want. Just create a new
color object:
Color c = new Color(140,140,140);
This line of Java code creates a color object representing a
dark grey.
You can use any combination of red, green, and blue
values to construct a color object.
Alternatively, you can also create a color object
using three floats from 0.0 to 1.0
Color c = new Color(0.34, 1.0, 0.25) ;
// first parameter represents the hue,
// second parameter represents the saturation.
// and the third represents brightness

Testing and Setting the Current


To draw an object or text using a color object, you have to
Colors

set the current color to be that color object, just as you


have to set the current font to the font in which you want to
draw.
Use the setColor method (a method for Graphics objects) to
do this:
g.setColor(Color.green);
After setting the current color, all drawing operations will
occur in that color.
In addition to setting the current color for the graphics
context, you can also set the background and foreground
colors for the applet itself by using the setBackground()
and setForeground() methods. Both of these methods are
defined in the java.awt.Component class.
The setBackground method sets the background color of
the applet, which is usually a dark grey. It takes a single
argument, a color object:
setBackground(Color.white);

Cont.

The setForeground() method also takes a single color as


an argument, and affects everything that has been drawn on
the applet, regardless of the color in which it has been
drawn.
setForeground(Color.black);
In addition to the setColor(), setForeground(), and
setBackground() methods, there are corresponding get
methods that enable you to retrieve the current graphics
color, background, or foreground. Those methods are
getColor() (defined in Graphics objects), getForeground()
(defined in Applet), and getBackground() (also in Applet).
You can use these methods to choose colors based on
existing colors in the applet:
setForeground(g.getColor());

Simple Animation and Threads


Topics:
How Java animations workthe paint(),
update() and repaint() methods, starting and
stopping dynamic applets, and how to use
and override these methods in your own
applets.
Threadswhat they are and how they can
make your applets more well-behaved with
other applets and with the Java system in
general?
Reducing animation flicker, a common
problem with animation in Java

repaint() method
An applet writes to its window only when paint()
method is called by the AWT.
How can the applet itself causes its window to be
updated when its information changes?
For example:
if an applet is displaying a moving banner (the coordinates of
the string are changing continuously).
If a string has to be displayed with different colors.

What mechanism does the applet use to update the


window each time, as in above cases?
repaint() methods is used when an applet needs to
update the information displayed in its window.

Different forms of repaint()


method
void repaint()
Causes the entire window to be repainted.
void repaint(int left, int top, int width, int height)
This version specifies a region that will be
repainted.

Starting and Stopping an Applets


Execution
start() and stop() are the methods that trigger your applet to
start and stop running. You didnt use start() and stop() in
previous examples, because the applets did nothing except
paint once. With animations and other Java applets that are
actually processing and running over time, youll need to
make use of start() and stop() to trigger the start of your
applets execution, and to stop it from running when you
leave the page that contains that applet. For most applets,
youll want to override start and stop for just this reason.
The start() method triggers the execution of the applet. You
can either do all the applets work inside that method, or you
can call other objects methods in order to do so.
Usually, start() is used to create and begin execution of a
thread so the applet can run in its own time.
stop(), on the other hand, suspends an applets execution so
when you move off the page on which the applet is
displaying, it doesnt keep running and using up system
resources. Most of the time when you create a start()

Digital
clock applet version 1 (Without using
import java.awt.*;
import java.util.Date;
thread)
public class DigitalVersion1 extends java.applet.Applet
{
Font theFont ;
Date theDate;
public void init()
{
theFont = new Font("TimesRoman", Font.BOLD,24) ;
theDate = null;
}
public void start()
{
while (true)
{
theDate = new Date();
repaint();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) { }
}
}

Cont.
public void paint(Graphics g)
{
g.setFont(theFont);
g.drawString(theDate.toString(),10,50) ;
}
}

Cont.
Using threads in Java, you can create an
applet so that it runs its own thread read
and it will run itself happily without
interfering with any other part of the
system.
A general thumb rule is that if you have
any bit of processing that is likely to
continue for a long time (such as
animation loop), put it in a thread.

Digital Clock version 2 (without stop() method)


import java.awt.Graphics;
import java.awt.Font;
import java.util.Date;
Import java.applet.Applet ;
public class DigitalVersion2 extends Applet implements
Runnable
{
Font theFont ;
Date theDate;
Thread runner;
public void init()
{
theFont = new
Font("TimesRoman",Font.BOLD,24);
theDate = null;
runner = new Thread(this);
}
public void start()
{
runner.start();

Cont
public void run()
{
while (true)
{
theDate = new Date();
repaint();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) { }
}
}
public void paint(Graphics g)
{
g.setFont(theFont);
g.drawString(theDate.toString(),10,50)
}
} // End of the class

After minimizing the applet window

Digital clock applet version: 3 (inclusion of stop()


import java.awt.Graphics;
method)
import java.awt.Font;
import java.util.Date;
public class DigitalVerson3 extends java.applet.Applet implements Runnable
{
Font theFont ;
Date theDate;
Thread runner;
public void init()
{ theFont = new Font(TimesRoman, Font.BOLD, 24);
runner = null;
}
public void start()
{
if (runner == null);
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}

Cont.
public void run()
{
while (true)
{
theDate = new Date();
repaint();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) { }
}
}
public void paint(Graphics g)
{
g.setFont(theFont);
g.drawString(theDate.toString(), 10, 50);
}
}

DigitalVersion3.html
<HTML>
<HEAD>
<TITLE>Welcome Java Applet</TITLE>
</HEAD>
<BODY>
<APPLET
code = DigitalVersion3.class"
width = 400
height = 100>
</APPLET>
</BODY>
</HTML>

Heres an example of an applet ColorSwirl that prints a single


string to the screen but that string is presented in different
colors that fade into each other dynamically.

Steps required:
1. Suppose you have to display a string with 50 different colors.
2. Define an array of 50 objects of Color class.
3. Insert the color values into that array.
4. Set the foreground color to first color value.
5. Call the repaint() method to trigger the paint() method.
6. The paint() method in turn will draw the string with specified
foreground color.
7. Repeat the steps 4 to 6 again and again with new color values.

The ColorSwirl applet


import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class ColorSwirl extends java.applet.Applet implements Runnable
{
Font f;
Color colors[] ;
Thread runThread ;
public void init()
{
f = new Font(TimesRoman,Font.BOLD,48);
colors= new Color[50];
runThread = null;
}
public void start()
{
if (runThread == null)
{
runThread = new Thread(this);
runThread.start();
}
}
public void stop()
{
if (runThread != null)
{
runThread.stop();
runThread = null;
}
}

Cont.

public void run()


{
// initialize the color array
float c = 0f;
for (int i = 0; i < colors.length; i++)
{
colors[i] =Color.getHSBColor(c, (float)1.0,
(float)1.0) ;
c += 0.02;
}
// cycle through the colors
int i = 0;
while (true)
{
setForeground(colors[i]);
repaint();
i++;
try
{
Thread.sleep(50);
}
catch (InterruptedException e) { }
if (i == colors.length )
i = 0;
}
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawString(All the Swirly Colors, 15,50);
}

Cont.
When the applet starts, the first thing you do is to create
an array of Color objects that contains all the colors the
text will display. By creating all the colors beforehand you
can then just draw text in, one at a time; its faster to
pre-compute all the colors at once.
To create the different colors, a method in the Color class
called getHSBColor() creates a color object based on
values for hue, saturation, and brightness, rather than the
standard red, green, and blue. This is easier; by
incrementing the hue value and keeping saturation and
brightness constant you can create a range of colors
without having to know the RGB for each one. If you dont
understand this, dont worry about it; its just an easy way
to create the color array.
The applet then cycles through the array of colors, setting
the foreground to each one in turn and calling repaint.
When it gets to the end of the array, it starts over again,
so the process repeats over and over.

A moving banner Applet


import java.awt.* ;
import java.applet.* ;
public class SimpleBanner extends Applet implements Runnable
{
String msg ;
Thread t ;
public void init()
{
msg = new String("A Simple Moving Banner ");
t = null;
}
public void start()
{
if(t == null)
{
t = new Thread(this);
t.start();
}
}
public void stop()
{
if(t != null)
{
t.stop();
t = null ;
}
}

Cont.
public void run()
{
char ch = ;
while (true) // cycle through the colors
{
repaint();
try
{
Thread.sleep(250);
}
catch(InterruptedException e) { }
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch ;
}
}
public void paint(Graphics g)
{
g.drawString(msg, 50, 30);
}
} // End of the class

Example: A scrolling string with color swirl


import java.awt.* ;
import java.applet.* ;
public class SimpleBanner2 extends Applet implements Runnable
{
String msg ;
Thread t ;
Color color[ ];
public void init()
{
t = null;
color = new Color[50] ;
msg = new String("A Simple Moving Banner ");
}
public void start()
{
if(t == null)
{
t = new Thread(this);
t.start();
}
}
public void stop()
{
if(t != null)
{
t.stop();
t = null ;
}
}

public void run()


{
char ch = ';
float c = 0.0F;
for (int i = 0; i < color.length; i++)
{
// for hue, saturation & brightness
color[i] =Color.getHSBColor(c, (float)1.0,
(float)1.0) ;
c += .02;
}

msg.length());

int i = 0;
while (true) // cycle through the colors
{
setForeground(color[i]);
repaint();
i++;
try
{
Thread.sleep(50);
}
catch (InterruptedException e) { }
if (i == color.length )
i = 0;
try
{
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1,
msg += ch ;

}
catch(InterruptedException e) { }

public void update(Graphics g)


{
paint(g);
}
public void paint(Graphics g)
{
g.drawString(msg, 50, 30);
}

} // End of the class

A moving checker applet


import java.awt.Graphics;
import java.awt.Color;
public class Checkers extends java.applet.Applet implements Runnable
{
Thread runner ;
int xpos;
public void init()
{
runner = null;
}
public void start()
{
if (runner == null);
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}

Cont.
public void run()
{
while(true)
{
for(xpos=5; xpos <=105; xpos=xpos+4)
{
repaint();
try
{ Thread.sleep(100); }
catch(InterruptedException e) {
}
for(xpos = 105; xpos > 5; xpos = xpos-4)
{
repaint();
try
{
Thread.sleep(100) }
catch(InterruptedException e) {
}
}
}

Cont.
public void paint(Graphics g)
{
//draw squares
g.setColor(Color.black);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.white);
g.fillRect(101, 0, 100, 100);
//draw checker
g.setColor(Color.magenta);
g.fillOval(xpos, 5, 90, 90);
}
}

Flicker and How to Avoid It


One can also observe an annoying flicker while running an
animated applet.
Flicker is caused by the way Java paints and repaints each
frame of an applet.
In the previous slides we had learnt that a repaint() method
calls the paint() method. Thats not precisely true.
A call to paint() does indeed occur in response to a
repaint(), but what actually happens are the following steps:
1.
The call to repaint() method results in a call to the update()
method.
2.
The update() method clears the screen of any existing
contents (in essence,
fills it with the current background
color), and then calls paint().
3.
The paint() method then draws the contents of the current
frame.

In Step 2, the call to update(), causes an animation flicker.


Because the screen is cleared between frames, the parts of
the screen that do not change alternate rapidly between
being painted and being cleared. Hence, flickering.

Function of update() method


1. Clear the applets window screen
Fill up the screen with current background color

2. Set the foreground color

3. Call the paint() method with current values of the image to be drawn

Cont.

Expected Animation

Actual outcome

Clear the screen (Fill up the screen


with current background color)

Repaint the screen with


current foreground color

update() method
The cause of flickering lies in the update() method.
The default version of update() method is:
public void update(Graphics g)
{
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
g.setColor(getForeground());
paint(g);
}
Basically, update() clears the screen (or, to be exact, fills
the applets bounding rectangle with the background
color), sets things back to normal, and then calls paint().

Calling Structure of repaint(), update() and


paint()
repaint()
schedules
update(Graphics g)
calls
paint(Graphics g)

A flow chart depicting the call to repaint(), update() and paint()


methods
start

call to repaint()

Send a request to thread for calling update()

wait for 100 milliseconds

call update()
call paint()
end

A flow chart depicting the call to repaint(), update() and paint()


methods
start

call to repaint()

is previous call to update() pending?

No
Send a request to thread for calling update()

wait for 100 milliseconds

call update()
call paint()
end

Yes

Calling of repaint(), update() and paint()


methods
So far we have said that repaint() method calls

the

paint() method; but in actual it is not so.


First time a call is made to the repaint() method, a
request is sent for a thread to call an update() method.
It will take 100 milliseconds to call an update() method.
When the repaint() method is called again, repaint()
also checks to see whether an update() is pending or
not.
If an update() method is pending, the repaint() method returns.
If no update() method is pending, then other call is scheduled.

As a result, update() is never called more than 10 time


per second, no matter how many calls are made to the
repaint() method.

Three ways to avoid flicker in your Java


applets
1. Override update() method so as to avoid the
clearing of screen.
2. Override update() method to clear only that part
of the screen that is changing during animation.
3. Override both update() and paint() methods and
use double-buffering.

First Solution: Dont Clear the Screen


The first solution to reducing flicker is not to
clear the screen at all. This works only for
some applets.
Now, recall the previously discussed ColorSwirl applet.
This applet flickers terribly when it is run.
Flicker in this applet appears because each time the
applet is painted, theres a moment where the screen is
cleared.
Instead of the text cycling neatly from red to a nice pink
to purple, its going from red to grey, to pink to grey, to
purple to grey, and so onnot very nice looking at all.

Output of the CurlySwirl Applet


Expected Output:
Step: 1

The Color Swirl

Step: 2

The Color Swirl

Step: 3

The Color Swirl

Actual Output:
Step: 1

The Color Swirl

Step: 2

The Curly Swirl

Step: 3

The Color Swirl

Fixing the flicker, using the first


method

Because the screen clearing is all thats causing the


problem, the solution is easy: override update() and remove
the part where the screen gets cleared. It doesnt really
need to get cleared anyhow, because nothing is changing
except the color of the text. With the screen clearing
behavior removed from update(), all update needs to do is
call paint(). Heres what the update() method looks like in
this applet:
public void update(Graphics g)
{
paint(g);
}

Example 1: When two same strings of same


font but of different colors are drawn,
starting from the same pixel positions
import java.awt.* ;
import java.applet.Applet ;
public class BackTest2 extends Applet
{
Font f ;
public void init()
{
f = new Font("TimesRoman", Font.BOLD, 35);
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString("This is the first string", 20, 200);
g.setColor(Color.blue);
g.drawString("This is the first string", 20, 200);
}
}

Output

Example 2: Two different strings starting from


the same pixel positions
import java.awt.* ;
import java.applet.Applet ;
public class BackTest extends Applet
{
Font f ;
public void init()
{
f = new Font("TimesRoman", Font.BOLD, 35);
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString("This is the first string", 20, 50);
g.setColor(Color.blue);
g.drawString("This is the second string", 20, 50);
}
}

Output:

Solution Two: Redraw Only What You


Have To
For some applets, it wont be quite that easy.
Heres another example. In this applet, called
Checkers, a red oval (a checker piece) moves
from a black square to a white square, as if on a
checkerboard.

Sol 2: Redraw only what you have to

Stage 1

Stage 2

Cont.

Step 1

Step 2

Step 3

1. Clip the rectangular area covering the previous position of the filled circle.
2. Clear this rectangular area only.
3. Paint the image with the current position of the circle.

Cont.
An instance variable, xpos, keeps track of the current starting position of
the checker (because it moves horizontally, the y stays constant and the
x changes). In the run() method, you change the value of x and repaint,
waiting 50 milliseconds between each move. The checker moves from
one side of the screen to the other and then moves back (hence the two
for loops in that method).
In the actual paint() method, the background squares are painted (one
black and one white), and then the checker is drawn at its current
position. This applet, like the Swirling Colors applet, also has a terrible
flicker. (In line 25, the background is blue to emphasize it, so if you run
this applet youll definitely see the flicker.)
However, the solution to solving the flicker problem for this applet is more
difficult than for the last one, because you actually want to clear the
screen before the next frame is drawn. Otherwise, the red checker wont
have the appearance of leaving one position and moving to another; itll
just leave a red smear from one side of the checkerboard to the other.

Cont.
How do you get around this? You still clear the screen, in order to get the
animation effect, but, rather than clearing the entire screen, you clear only
the part that you actually changed.
By limiting the redraw to only a small area, you can eliminate much of the
flicker you get from redrawing the entire screen.
To limit what gets redrawn, you need a couple of things. First, you need a
way to restrict the drawing area so that each time paint() is called, only the
part that needs to get redrawn actually gets redrawn. This can be achieved
by using a mechanism called clipping.
Clipping, part of the graphics class, enables you to restrict the drawing area
to a small portion of the full screen; although the entire screen may get
instructions to redraw, only the portions inside the clipping area are actually
drawn.
The second thing you need is a way to keep track of the actual area to
redraw. Both the left and right edges of the drawing area change for each
frame of the animation (one side to draw the new oval, the other to erase the
bit of the oval left over from the previous frame), so to keep track of those
two x values, you need instance variables for both the left side and the right.

Checker Applet version 2 (with reduction of


import java.awt.Graphics;
flicker)
import java.awt.Color;
public class Checkers2 extends java.applet.Applet implements
Runnable
{
Thread runner;
int xpos;
int ux1,ux2;
public void start()
{
if (runner == null)
{
runner = new Thread(this) ;
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}

Cont.

public void run()


{
setBackground(Color.blue);
while (true)
{
for (xpos = 5; xpos <= 105; xpos+=4)
{
ux2 = xpos + 90;
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
if (ux1 == 0) ux1 = xpos;
}
for (xpos = 105; xpos > 5; xpos -=4)
{
ux1 = xpos;
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
if (ux2 == 0)
ux2 = xpos + 90;
}
}
}

Cont.
public void update(Graphics g)
{
g.clipRect(ux1, 5, ux2 - ux1, 95);
paint(g);
}
public void paint(Graphics g)
{
// Draw squares
g.setColor(Color.black);
g.fillRect(0,0,100,100);
g.setColor(Color.white);
g.fillRect(101,0,100,100);
// Draw checker
g.setColor(Color.red);
g.fillOval(xpos,5,90,90);
// reset the drawing area
ux1 = ux2 = 0;
}
}

The HTML APPLET Tag


<APPLET
[CODEBASE=codebaseURL]
CODE=appletFile
WIDTH=pixel HEIGHT = pixel
[ALIGN = alignment]
[VSPACE=pixels] [HSPACE=pixels]

>
[<PARAM
NAME
=
VALUE=AttributeValue>]
[<PARAM
NAME
=
VALUE=AttributeValue>]
---------[HTML Displayed in the absence of Java]
</APPLET>

AttributeName1
AttributeName2

Cont.
CODEBASE
If you want to store your class files in a different directory
than that of your HTML files, you have to tell the Javacapable browser where to find those class files. To do this,
you use CODEBASE.
CODE contains only the name of the class file; CODEBASE
contains an alternate pathname where classes are
contained. For example, if you store your class files in a
directory called /classes, which is in the same directory as
your HTML files, CODEBASE is the following:
<APPLET CODE=myclass.class CODEBASE=classes
WIDTH=100 HEIGHT=100>

CODE
It is used to indicate the name of the class file that holds
the current applet. If CODE is used alone in the
<APPLET> tag, the class file is searched for in the same
directory as the HTML file that references it.

Cont.
NAME
Name is an optional attribute used to specify a name for the
applet instance. 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 pixel) of the applet display area.

ALIGN
ALIGN is an optional attribute that specifies the alignment of
the applet. The possible values are: LEFT, RIGHT, TOP,
BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE and
ABSBOTTOM.

Cont.
PARAM NAME and VALUE
The PARAM tag allows you to specify applet specific arguments in
an HTML page. Applet access their attributes with the
getParameter() method.
Applet parameters come in two parts:

A name, which is simply a kind of identifier name you pick.


A value, which determines the value of that particular parameter.

For example, you can indicate the color of text in an applet by


using a parameter with the name=color and the value=red. You
can determine an animations speed using a parameter with the
name=speed and the value=5.
<PARAM> tag, which has two attributes for the name and the
value, called (surprisingly enough), NAME and VALUE. The
<PARAM> tag goes inside the opening and closing <APPLET> tags:
<APPLET CODE=MyApplet.class WIDTH =100 HEIGHT=100 >
<PARAM NAME = font VALUE=TimesRoman>
<PARAM NAME = size VALUE=36">
</APPLET>

Cont.
This particular example defines two parameters to the
MyApplet applet: one whose name is font and whose value is
TimesRoman, and one whose name is size and whose value is
36.
Those parameters are passed to your applet when it is loaded.
In the init() method for your applet, you can then get hold of
those parameters by using the getParameter() method.
getParameter() takes one argumenta string representing
the name of the parameter youre looking forand returns a
string containing the corresponding value of that parameter.
(Like arguments in Java applications, all the parameter values
are converted to strings.) To get the value of the font parameter
from the HTML file, you might have a line such as this in your
init() method:
String theFontName = getParameter(font);

Example
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class MoreHelloApplet extends java.applet.Applet
{
Font f ;
String str ;
public void init()
{
f = new Font(TimesRoman, Font.BOLD, 36);
str = getParameter(name);
str = Hello + str + !;
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(Color.red);
g.drawString(name, 5, 50);
}
}

Cont.

<HTML>
<HEAD>
<TITLE>Hello!</TITLE>
</HEAD>
<BODY>
<P>
<APPLET CODE=MoreHelloApplet.class
WIDTH=300 HEIGHT=50>
<PARAM NAME=name VALUE=Martin Crowe>
</APPLET>
</BODY>
</HTML>

Retrieving and Using Images

Basic image handling in Java is easy.


The Image class in java.awt provides
an abstract methods to represent
common image behavior, and special
methods defined in Applet and
Graphics give you everything you
need to load and display images in
your applet as easily as drawing a
rectangle.

Getting Images

In order to display an image in your applet, you first


need to load that image into your Java program.

Images are stored as separate files from your Java class


files, so you have to tell Java where to find them.

The Applet class provides a method called getImage(),


which loads an image and automatically creates an
instance of the Image class for you. To use it, all you
have to do is import the java.awt.Image class, and
then give getImage() the URL of the image you want to
load. There are two ways of doing this:
1.
2.

The getImage() method with a single argument (an


object of type URL) retrieves the image at that URL.
The getImage() method with two arguments: the base
URL (also a URL object) and a string representing the
path or filename of the actual image (relative to the
base).

Cont.

The Applet class also provides two methods that will help with the
base URL argument to getImage:
The getDocumentBase() method returns a URL object representing the
directory of the HTML file that contains this applet. So, for example, if
the HTML file is located at
http://www.myserver.com/htmlfiles/javahtml/
getDocumentBase() method returns a URL pointing to that path.
The getCodeBase() method returns a string representing the directory
in which this applet is containedwhich may or may not be the same
directory as the HTML file, depending on whether the CODEBASE
attribute in <APPLET> is set or not.
Whether you use getDocumentBase() or getCodebase() depends on
whether your images are relatived to your HTML files or relative to your
Java class files. Use whichever one applies better to your situation. Note
that either of these methods is more flexible than hard-coding a URL or
pathname into the getImage method; using either getDocumentBase or
getCodeBase enables you to move your HTML files and applets around
and Java can still find your images.

Cont.
Here are a few examples of getImage, to give you an idea of how
to use it. This first call to getImage retrieves the file at that
specific URL (http://www.server.com/files/image.gif). If any part
of that URL changes, you have to recompile your Java applet to
take the new path into account:
Image img = getImage(new
URL(http://www.server.com/files/image.gif));
In the following form of getImage, the image.gif file is in the same
directory as the HTML files that refer to this applet:
Image img = getImage(getDocumentBase(), image.gif) ;
In this similar form, the file image.gif is in the same directory as
the applet itself:
Image img = getImage(getCodeBase(), image.gif) ;

Cont.
If you have lots of image files, its common to put
them into their own subdirectory. This form of
getImage() looks for the file image.gif in the
directory images, which, in turn, is in the same
directory as the Java applet:
Image
img
images/image.gif) ;

getImage(getCodeBase(),

If Java cant find the file youve indicated,


getImage() returns null. Your program will continue
to runyou just wont see that image on your
screen when you try to draw it.

Example:

import java.awt.*;
import java.applet.*;
public class URLDemo extends Applet
{
public void paint(Graphics g)
{
String msg;
URL url=getCodeBase();
msg = "Code Base : "+url.toString();
g.drawString(msg,10,20);
url=getDocumentBase();
msg="Document Base : "+ url.toString();
g.drawString(msg,10,40);
}
}

Output:

Drawing Images
The Graphics class provides two methods to do just that,
both called drawImage()
The first version of drawImage takes four arguments: the
image to display, the x and y positions of the top left corner,
and this:
void paint()
{
g.drawImage(img, 10, 10, this);
}
This first form draws the image in its original dimensions
with the top left corner at the given x and y positions

Example: The following Java program shows the code for a very
simple applet that loads in an image called ladybug.gif and
displays it.
import java.awt.Graphics;
import java.awt.Image;
public class LadyBug extends java.applet.Applet
{
Image bugimg;
public void init()
{
bugimg
=
getImage(getCodeBase(),
images/ladybug.gif);
}
public void paint (Graphics g)
{
g.drawImage(bugimg,10,10,this);
}
}

Cont.
The second form of drawImage() takes six
arguments: the image to draw, the x and y
coordinates, a width and height of the image
bounding box, and this. If the width and height
arguments for the bounding box are smaller or
larger than the actual image, the image is
automatically scaled to fit.
Using those extra arguments enables you to
squeeze and expand images into whatever
space you need them to fit in (keep in mind,
however, that there may be some image
degradation from scaling it smaller or larger
than its intended size).

Cont.
One helpful hint for scaling images is to find out the
size of the actual image that youve loaded, so you
can then scale it to a specific percentage and avoid
distortion in either direction.
Two methods defined for the Image class enable you
do this: getWidth() and getHeight().
Both take a single argument, an instance of
ImageObserver, which is used to track the loading of
the image (more about this later).
Most of the time, you can use just this as an
argument to either getWidth() or getHeight()
If you stored the ladybug image in a variable called
bugimg, for example, this line returns the width of
that image, in pixels:
theWidth = bugimg.getWidth(this);

Example
import java.awt.Graphics;
import java.awt.Image;
public class LadyBug2 extends java.applet.Applet
{
Image bugimg;
public void init()
{
bugimg = getImage(getCodeBase(), images/ladybug.gif);
}
public void paint(Graphics g)
{
int iwidth = bugimg.getWidth(this);
int iheight = bugimg.getHeight(this);
int xpos = 10;
// 25 %
g.drawImage(bugimg,xpos,10, iwidth / 4, iheight / 4, this);

Cont.
// 50 %
xpos += (iwidth / 4) + 10;
g.drawImage(bugimg, xpos , 10, iwidth / 2, iheight / 2, this);
// 100%
xpos += (iwidth / 2) + 10;
g.drawImage (bugimg, xpos, 10, this);
// 150% x, 25% y
g.drawImage(bugimg, 10, iheight + 30, (int)(iwidth * 1.5),
iheight / 4, this);
}
}

When running inside a web browser the size


of an applet is set by the height and width
attributes and cannot be changed by the
applet.
Many applets need to know their own size.
Retrieving the applet size is straightforward
with the getSize() method.
java.applet.Applet inherits this method from
java.awt.Component.
The
getSize()
method
returns
a
java.awt.Dimension object.
A Dimension object has two public int fields,
height and width.

Finding an Applet's Size

Example

import java.applet.*;
import java.awt.*;
public class SizeApplet extends Applet
{
public void paint(Graphics g)
{
Dimension appletSize = this.getSize();
int appletHeight = appletSize.height;
int appletWidth = appletSize.width;
g.drawString(Applet Height = " + appletHeight, 10,
20);
g.drawString(Applet Width = + appletWidth, 10, 40);
}
}

Animating a Neko
Functions of Neko:
Runs in from the left side of the screen
Stops in the middle and yawns
Scratches its ear four times
Sleeps a little
Wakes up and runs off to the right side of the
screen

Neko images
right1

right2

stop

yawn

scratch1

scratch2

sleep1

sleep2

awake

Example: Animating an image

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
public class Neko extends java.applet.Applet implements Runnable
{
Image nekopics[] = new Image[9];
Image currentimg;
Thread runner;
int xpos;
int ypos ;
public void init()
{
xpos = 0;
ypos = 50;
setBackground(Color.white);
String nekosrc[] = { "right1.gif", "right2.gif","stop.gif",
"yawn.gif",
"scratch1.gif","scratch2.gif","sleep1.gif",
"sleep2.gif", "awake.gif" };
for (int i=0; i < nekopics.length; i++)
{
nekopics[i] = getImage(getCodeBase(), "neko/"
+
nekosrc[i]);

Cont.
public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null)
{
runner.stop();
runner = null;
}
}

Cont. public void run()

{
currentimg=nekopics[0] ; // run from one side of the
screen to the middle

nekorun(0, this.getSize().width / 2);


currentimg = nekopics[2]; // stop and pause
repaint();
pause(1000);
currentimg = nekopics[3]; // yawn
repaint();
pause(1000);
nekoscratch(4); // scratch four times
nekosleep(5); // sleep for 5 "turns"
currentimg = nekopics[8]; // wake up and run off
repaint();
pause(500);
currentimg = nekopics[0] ;
nekorun(xpos, this.getSize().width + 10);

Cont.
public void nekorun(int start, int end)
{
for (int i = start; i < end; i += 10)
{
xpos = i;
// swap images
if (currentimg == nekopics[0])
currentimg = nekopics[1];
else if (currentimg == nekopics[1])
currentimg = nekopics[0];
repaint();
pause(150);
}
}

Cont.

pubilc void nekoscratch(int numtimes)


{
for (int i =1; i <= numtimes; i++)
{
currentimg = nekopics[4];
repaint();
pause(150);
currentimg = nekopics[5];
repaint();
pause(150);
}
}

Cont.
public void nekosleep(int numtimes)
{
for (int i = numtimes; i > 0; i--)
{
currentimg = nekopics[6];
repaint();
pause(250);
currentimg = nekopics[7];
repaint();
pause(250);
}
}

Cont.
public void pause(int time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e) { }
}
public void paint(Graphics g)
{
g.drawImage(currentimg, xpos, ypos,
this);
}
}

Retrieving and Using Sounds


The simplest way to retrieve and play a sound is
through the play() method, part of the Applet
class and therefore available to you in your
applets. The play() method is similar to the
getImage method in that it takes one of two
forms:
play() with one argument, a URL object, loads
and plays the given audio clip at that URL.
play() with two arguments, one a base URL and
one a pathname, loads and plays that audio
file. The first argument can most usefully be
either a call to getDocumentBase() or
getCodeBase().

Cont.
For example, the following line of
code retrieves and plays the sound
meow.au, which is contained in the
audio directory. The audio directory,
in turn, is located in the same
directory as this applet:
play(getCodeBase(),
audio/meow.au);

Cont.
If you want to play a sound repeatedly, start and
stop the sound clip, or run the clip as a loop (play it
over and over), things are slightly more complicated
but not much more so. In this case, you use the
applet method getAudioClip() to load the sound clip
into an instance of the class AudioClip (part of
java.appletdont forget to import it) and then
operate directly on that AudioClip object.
Suppose, for example, that you have a sound loop
that you want to play in the background of your
applet. In your initialization code, you can use this
line to get the audio clip:
AudioClip clip = getAudioClip(getCodeBase(),
audio/loop.au);

Cont.

To stop a currently playing sound clip, use the stop() method:


clip.stop();
To loop the clip (play it repeatedly), use the loop() method:
clip.loop();
If the getAudioClip method cant find the sound you indicate, or
cant load it for any reason, the AudioClip variable is set to null.
Its a good idea to test for this case in your code before trying to
play the audio clip, because trying to call the play(), stop(), and
loop() methods on a null object will result in an error (actually, an
exception).
In your applet, you can play as many audio clips as you need; all
the sounds you use play concurrently as your applet executes.
Note that if you use a background sounda sound clip that loops
repeatedlythat sound clip will not stop playing automatically
when you suspend the applets thread. This means that even if
your reader moves to another page, the first applets sounds will
continue to play.
You can fix this problem by stopping the applets background
sound in your stop() method:

Cont.
public void stop()
{
if (runner != null)
{
if (bgsound!= null)
bgsound.stop();
runner.stop();
runner = null;
}
}

The complete program


import java.awt.Graphics;
import java.applet.AudioClip;
public class AudioLoop extends java.applet.Applet
implements Runnable
{
AudioClip bgsound;
AudioClip beep;
Thread runner;
public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}

Cont.
public void stop()
{
if (runner != null)
{
if (bgsound != null)
bgsound.stop();
runner.stop();
runner = null;
}
}
public void init()
{
bgsound = getAudioClip(getCodeBase(),audio/loop.au);
beep = getAudioClip(getCodeBase(), audio/beep.au);
}

Cont.

public void run()


{
if (bgsound != null)
bgsound.loop();
while (runner != null)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e) { }
if (bgsound != null)
beep.play();
}
}
public void paint(Graphics g)
{
g.drawString(Playing Sounds...., 10, 10);
}
}

S-ar putea să vă placă și