Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Online Training

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 
Training Index

JavaTM Programming Language Basics, Part 1
Lesson 3: Building Applets

[<<BACK] [CONTENTS] [NEXT>>]

Like applications, applets are created from classes. However, applets do not have a main method as an entry point, but instead, have several methods to control specific aspects of applet execution.

This lesson converts an application from Lesson 2 to an applet and describes the structure and elements of an applet.


Application to Applet

The following code is the applet equivalent to the LessonTwoB application from Lesson 2. The figure below shows how the running applet looks. The structure and elements of the applet code are discussed after the section on how to run the applet just below.

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class SimpleApplet extends Applet{

  String text = "I'm a simple applet";

  public void init() {
        text = "I'm a simple applet";
        setBackground(Color.cyan);
  }
  public void start() {
        System.out.println("starting...");
  }
  public void stop() {
        System.out.println("stopping...");
  }
  public void destroy() {
        System.out.println("preparing to unload...");
  }
  public void paint(Graphics g){
        System.out.println("Paint");
        g.setColor(Color.blue);
        g.drawRect(0, 0,
                   getSize().width -1,
                   getSize().height -1);
        g.setColor(Color.red);
        g.drawString(text, 15, 25);
  }
}
The SimpleApplet class is declared public so the program that runs the applet (a browser or appletviewer), which is not local to the program can access it.

Run the Applet

To see the applet in action, you need an HTML file with the Applet tag as follows:

<HTML>
<BODY>
<APPLET CODE=SimpleApplet.class WIDTH=200 HEIGHT=100>
</APPLET>
</BODY>
</HTML>

The easiest way to run the applet is with appletviewer shown below where simpleApplet.html is a file that contains the above HTML code:

   appletviewer simpleApplet.html

Note: To run an applet written with JavaTM 2 APIs in a browser, the browser must be enabled for the Java 2 Platform. If your browser is not enabled for the Java 2 Platform, you have to use appletviewer to run the applet or install Java Plug-in. Java Plug-in lets you run applets on web pages under the 1.2 version of the Java VM instead of the web browser's default Java VM.

Applet Structure and Elements

The Java API Applet class provides what you need to design the appearance and manage the behavior of an applet. This class provides a graphical user interface (GUI) component called a Panel and a number of methods. To create an applet, you extend (or subclass) the Applet class and implement the appearance and behavior you want.

The applet's appearance is created by drawing onto the Panel or by attaching other GUI components such as push buttons, scrollbars, or text areas to the Panel. The applet's behavior is defined by implementing the methods.

Extending a Class

Most classes of any complexity extend other classes. To extend another class means to write a new class that can use the fields and methods defined in the class being extended. The class being extended is the parent class, and the class doing the extending is the child class. Another way to say this is the child class inherits the fields and methods of its parent or chain of parents. Child classes either call or override inherited methods. This is called single inheritance.

The SimpleApplet class extends Applet class, which extends the Panel class, which extends the Container class. The Container class extends Object, which is the parent of all Java API classes.

The Applet class provides the init, start, stop, destroy, and paint methods you saw in the example applet. The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. The Applet class provides no functionality for these methods.

However, the Applet class does provide functionality for the setBackground method,which is called in the init method. The call to setBackground is an example of calling a method inherited from a parent class in contrast to overriding a method inherited from a parent class.

You might wonder why the Java language provides methods without implementations. It is to provide conventions for everyone to use for consistency across Java APIs. If everyone wrote their own method to start an applet, for example, but gave it a different name such as begin or go, the applet code would not be interoperable with other programs and browsers, or portable across multiple platforms. For example, Netscape and Internet Explorer know how to look for the init and start methods.

Behavior

An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be appletviewer as you saw in the example. The underlying software controls the applet by calling the methods the applet inherits from the Applet class.

The init Method: The init method is called when the applet is first created and loaded by the underlying software. This method performs one-time operations the applet needs for its operation such as creating the user interface or setting the font. In the example, the init method initializes the text string and sets the background color.

The start Method: The start method is called when the applet is visited such as when the end user goes to a web page with an applet on it. The example prints a string to the console to tell you the applet is starting. In a more complex applet, the start method would do things required at the start of the applet such as begin animation or play sounds.

After the start method executes, the event thread calls the paint method to draw to the applet's Panel. A thread is a single sequential flow of control within the applet, and every applet can run in multiple threads. Applet drawing methods are always called from a dedicated drawing and event-handling thread.

The stop and destroy Methods: The stop method stops the applet when the applet is no longer on the screen such as when the end user goes to another web page. The example prints a string to the console to tell you the applet is stopping. In a more complex applet, this method should do things like stop animation or sounds.

The destroy method is called when the browser exits. Your applet should implement this method to do final cleanup such as stop live threads.

Appearance

The Panel provided in the Applet class inherits a paint method from its parent Container class. To draw something onto the Applet's Panel, you implement the paint method to do the drawing.

The Graphics object passed to the paint method defines a graphics context for drawing on the Panel. The Graphics object has methods for graphical operations such as setting drawing colors, and drawing graphics, images, and text.

The paint method for the SimpleApplet draws the I'm a simple applet string in red inside a blue rectangle.

   public void paint(Graphics g){
        System.out.println("Paint");
//Set drawing color to blue
        g.setColor(Color.blue);
//Specify the x, y, width and height for a rectangle
        g.drawRect(0, 0,
                   getSize().width -1,
                   getSize().height -1);
//Set drawing color to red
        g.setColor(Color.red);
//Draw the text string at the (15, 25) x-y location
        g.drawString(text, 15, 25);
   }

Packages

The applet code also has three import statements at the top. Applications of any size and all applets use import statements to access ready-made Java API classes in packages. This is true whether the Java API classes come in the Java platform download, from a third-party, or are classes you write yourself and store in a directory separate from the program. At compile time, a program uses import statements to locate and reference compiled Java API classes stored in packages elsewhere on the local or networked system. A compiled class in one package can have the same name as a compiled class in another package. The package name differentiates the two classes.

The examples in Lessons 1 and 2 did not need a package declaration to call the System.out.println Java API class because the System class is in the java.lang package that is included by default. You never need an import java.lang.* statement to use the compiled classes in that package.

More Information

You can find more information on applets in the Writing Applets trail in The Java Tutorial.

[TOP]


Print Button
[ This page was updated: 31-Mar-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.