Chapter 4: Applets and Application: 4.1. Applet Fundamentals
Chapter 4: Applets and Application: 4.1. Applet Fundamentals
in Java
1. This applet begins with two import statements. The first imports the Abstract Window Toolkit
(AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT,
not through the console-based I/O classes. The AWT contains support for a window-based,
graphical user interface.
2. The second import statement imports the applet package, which contains the class Applet.
Every applet that we create must be a subclass of Applet.
3. The next line in the program declares the class SimpleApplet. This class must be declared as
public, because it will be accessed by code that is outside the program.
4. Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be
overridden by the applet. paint( ) is called each time that the applet must redisplay its output.
This situation can occur for several reasons. For example, the window in which the applet is
running can be overwritten by another window and then uncovered. Or, the applet window
can 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 contains the graphics context,
which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.
5. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method
outputs a string beginning at the specified X,Y location. It has the following general form:
Prepared By: Asst. Prof. Madan Kadariya (NCIT)
Page 1 of 12
Programming in Java
The width and height statements specify the dimensions of the display area used by the applet. After
the creation of this file, we can execute our browser and then load this file, which causes SimpleApplet
to be executed.
To execute SimpleApplet with an applet viewer, we may also execute the HTML file shown earlier.
For example, if the preceding HTML file is called RunApp.html, then the following command line
will run SimpleApplet:
C:\>appletviewer RunApp.html
However, a more convenient method exists that we can use to speed up testing. Simply include a
comment at the head of Java source code file that contains the APPLET tag. By doing so, our code is
documented with a prototype of the necessary HTML statements, and we can test our compiled applet
merely by starting the applet viewer with our Java source code file. The SimpleApplet source file
looks like this:
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);
}
}
Key Points
1. Applets do not need a main( ) method.
2. Applets must be run under an applet viewer or a Java-compatible browser.
3. User I/O is not accomplished with Javas stream I/O classes. Instead, applets use the
interface provided by the AWT or Swing.
4. All applets are subclasses (either directly or indirectly) of Applet.
5. Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer.
Prepared By: Asst. Prof. Madan Kadariya (NCIT)
Page 2 of 12
Programming in Java
6. Output is handled with various AWT methods, such as drawString(),which outputs a string
to a specified X,Y location, not by system.out.println().
7. A Java-enabled web browser will execute the applet when it encounters the APPLET tag
within the HTML file.
Page 3 of 12
Programming in Java
clipName)
void start( )
Page 4 of 12
Programming in Java
public void init()
public void
paint(Graphics g)
public void
destroy()
Called once by the applet container when an applet is loaded for execution.
This method initializes an applet. Typical actions performed here are
initializing fields, creating GUI components, loading sounds to play, loading
images to display and creating threads.
Called by the applet container after method init completes execution. In
addition, if the user browses to another website and later returns to the
applets HTML page, method start is called again. The method performs
any tasks that must be completed when the applet is loaded for the first time
and that must be performed every time the applets HTML page is revisited.
Actions performed here might include starting an animation or starting other
threads of execution.
Called by the applet container after methods init and start. Method paint is
also called when the applet needs to be repainted. For example, if the user
covers the applet with another open window on the screen and later uncovers
it, the paint method is called. Typical actions performed here involve
drawing with the Graphics object g thats passed to the paint method by the
applet container.
The applet container calls this method when the user leaves the applets
web page by browsing to another web page. Since its possible that the user
might return to the web page containing the applet, method stop performs
tasks that might be required to suspend the applets execution, so that the
applet does not use computer processing time when its not displayed on the
screen. Typical actions performed here would stop the execution of
animations and threads.
The applet container calls this method when the applet is being removed
from memory. This occurs when the user exits the browsing session by
closing all the browser windows and may also occur at the browsers
discretion when the user has browsed to other web pages. The method
performs any tasks that are required to clean up resources allocated to the
applet.
Page 5 of 12
Programming in Java
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}
CODEBASE is an optional attribute that specifies the base URL of the applet code, which is
the directory that will be searched for the applets executable class file. The HTML
documents 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 is a required attribute that gives the name of the file containing applets 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 CODEBASE if set.
ALT The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser recognizes the APPLET tag but cant currently run Java applets.
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 are required attributes that give the size (in pixels) of the applet
display area.
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.
Page 6 of 12
Programming in Java
VSPACE and HSPACE are optional attributes. VSPACE specifies the space, in pixels, above
and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.
Theyre treated the same as the IMG tags VSPACE and HSPACE attributes.
PARAM NAME and VALUE The PARAM tag allows us to specify applet-specific
arguments in an HTML page. Applets access their attributes with the getParameter( ) method.
Page 7 of 12
Programming in Java
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);
}
}
Page 8 of 12
Programming in Java
To sum up, Java has three separate mechanisms for enforcing security:
1. Program code is interpreted by the Java Virtual Machine, not executed directly.
2. A security manager checks all sensitive operations in the Java runtime library.
3. Applets can be signed to identify their origin.
4.10.Applet vs Application
Features
main() method
Application
Present
Applet
Not present
Execution
Requires JRE
Nature
Restrictions
Security
4.11.Advantages of Applet
Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in real-time programming (where as servlets require).
Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
In GUI development, constructor, size of frame, window closing code etc. are not required
(but are required in applications).
Page 9 of 12
Programming in Java
Displaying Images
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within
the applet, we use the drawImage method found in the java.awt.Graphics class. Following is the
example showing all the steps to show images:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this. getDocumentBase(),imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e. printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage( image, 0, 0, 200, 84, null);
g.drawString("www.appletdemos.com", 35, 100);
}
}
Playing Audio
An applet can play an audio file represented by the AudioClip interface in the java.applet package.
The AudioClip interface has three methods, including:
public void play: Plays the audio clip one time, from the beginning.
public void loop: Causes the audio clip to replay continually.
public void stop: Stops playing the audio clip.
To obtain an AudioClip object, we must invoke the getAudioClip method of the Applet class. The
getAudioClip method returns immediately, whether or not the URL resolves to an actual audio file.
The audio file is not downloaded until an attempt is made to play the audio clip.
Prepared By: Asst. Prof. Madan Kadariya (NCIT)
Page 10 of 12
Programming in Java
Page 11 of 12
Programming in Java
this case: AppletToApplication). This is now the constructor method for the class.
3. Delete the word void in the header of your new AppletToApplication constructor, since a
constructor has no return type.
4. Alter the class header so that it extends Frame rather than Applet (or JApplet) .
5. Create a new method called main. The header for this method will be:
public static void main (String[] args)
This method should create a Frame object as an instance of the class. So, if your class is named
AppletToApplication, the main method should look like the following (where the size will be
your original applet size):
public static void main(String[] args)
{
AppletToApplication f = new AppletToApplication ();
f.setSize(300,200);
f.setVisible(true);
f.setLayout(new FlowLayout());
}
6. Delete the import for the class Applet , since it is now redundant.
7. Add window methods (e.g., windowClosing to handle the event which is the user clicking on
the close window button, and others). This also involves adding implements
WindowListener and this.addWindowListener(this); to the new constructor method you
created in Step #2 above - in order to register the event handler.
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
public void windowOpened(WindowEvent e)
{ }
public void windowIconified(WindowEvent e)
{ }
public void windowClosed(WindowEvent e)
{ }
public void windowDeiconified(WindowEvent e)
{ }
public void windowActivated(WindowEvent e)
{ }
public void windowDeactivated(WindowEvent e)
{ }
8. Make sure that the program does not use any of the methods that are special to the Applet
class methods including getAudioClip , getCodeBase , getDocumentBase , and getImage.
Page 12 of 12