Applet 1
Applet 1
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
The Applet Class
The Applet class defines the methods
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.