Applet
Applet
Applet
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 ;
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
Execution of an applet
start
Life
Cycle of
an
Applet
init()
start()
paint()
No
Applet
disabled
?
Yes
stop()
Applet
enabled
?
No
destroy()
stop
Yes
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.
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.
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
Lines
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
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.
and
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);
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
Arc
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.
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
g.fillRect(0,250,290,290);
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);
}
Class
Function
getFont()
Graphic
s
object
getName( Font
)
getSize()
Font
as
getStyle() Font
isPlain()
Font
isBold()
Font
isItalic()
Font
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);
}
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
Cont.
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.
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.
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
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>
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.
Cont.
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.
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
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) { }
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);
}
}
3. Call the paint() method with current values of the image to be drawn
Cont.
Expected Animation
Actual outcome
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().
call to repaint()
call update()
call paint()
end
call to repaint()
No
Send a request to thread for calling update()
call update()
call paint()
end
Yes
the
Step: 2
Step: 3
Actual Output:
Step: 1
Step: 2
Step: 3
Output
Output:
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.
Cont.
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;
}
}
>
[<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.
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:
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>
Getting Images
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(),
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);
}
}
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
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;
}
}
{
currentimg=nekopics[0] ; // run from one side of the
screen to the middle
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.
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);
}
}
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.
Cont.
public void stop()
{
if (runner != null)
{
if (bgsound!= null)
bgsound.stop();
runner.stop();
runner = null;
}
}
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.