pixel
pixel
header
    February 28, 2003    

In this Issue

imageJava Programming Language Basics
imageJava Bits
imageMaking Sense of the Java Class Libraries
imageProgram Challenge
imageTake Online Quizzes
imageFor More Information

Pixel

Java Programming Language Basics

Understanding Applets

When Java technology was first announced, the biggest promise was in something called applets, little programs that ran within the browser to make web pages more interactive. Think back to 1995 here, where most web pages were static, and dynamic content consisted of Perl scripts that ran through the Common Gateway Interface (CGI). There wasn't much in the way of fancy, animated graphics, and any user interaction required another request-response cycle to go back to the web server. At the time, a company named Netscape dominated the browser market and was the first to license the Java runtime for their Navigator browser. Microsoft signed on and added their own virtual machine to support the execution of these Java programs in their browser, too.

Jump ahead a few years, and the world is again looking at applets as a way of deploying embedded programs for the browser. Since Sun's Java Plug-in can upgrade the old and incompatible virtual machine built into Internet Explorer to the latest Java Runtime Environment (JRE) through the Get Java Technology for your Desktop program, developers have again been embracing applet-based solutions.

But what exactly is an applet? Technically speaking, an applet is any class that extends from the Applet class in the java.applet package. That's literally it. There is certainly more to applets, but once you have this subclass, you can add it to a web page by identifying it within an <APPLET> - </APPLET> tag set. The browser will then load the applet class and display it in the designated space.

You also have the methods init, start, stop, and destroy. Since applet is a subclass of java.awt.Component, the paint method is also of interest for drawing the display area. The key five methods work as follows:

  • init - called when the browser loads the main applet class into the system. Typically, applets don't have a constructor. Instead, their one-time initialization code is here.
  • start - called when the applet should start execution, when the user visits the page containing the applet.
  • stop - called when the applet should stop execution, when the user is viewing a web page other than the page containing the applet.
  • destroy - called when the browser decides to unload the applet. Resources can be reclaimed here, but you have no control over when destroy is called.
  • paint - called when the browser determines the applet's display area is invalid.

To demonstrate, the following applet prints to the console when each of the five methods is called. The paint method also is used to paint a message on the display. For each time the paint method is called, the number increases. This does lead to the question of where messages written to the console can be found. This differs from browser to browser and sometimes from version to version. With Internet Explorer 6.0, the Sun Java Console is under the Tools menu. With the Microsoft runtime and IE6, the console is under the View menu. With the Netscape 7.0 and Mozilla browsers, you'll find the Java console under the Web Development menu (under the Tools menu).

Now the applet:

import java.awt.*;
import java.applet.*;

public class FirstApplet extends Applet {
        public void init() {
                System.out.println("In init()");
        }
        public void start() {
                System.out.println("In start()");
        }
        public void stop() {
                System.out.println("In stop()");
        }
        public void destroy() {
                System.out.println("In destroy()");
        }
        public synchronized void paint(Graphics g) {
                System.out.println("In paint()");
                g.drawString("Painting...", 50, 50);
        }
}

You compile the applet, just like any other source file:

javac FirstApplet.java

This will create FirstApplet.class, assuming the file has no errors.

Running an applet is a little different than with standalone programs. Instead of providing a main method to run once the file is loaded, you need to provide an HTML file to load the applet. This is where the <APPLET> tag comes into play. Here is what the tag definition looks like:

<APPLET
    // Required
    CODE = appletClass or 
    OBJECT = serializedApplet
    HEIGHT = pixels
    WIDTH = pixels  

    // Options
    CODEBASE = codebaseURL
    ARCHIVE = archiveList
    ALT = alternateText
    NAME = instanceName
    ALIGN = alignment
    HSPACE = pixels
    VSPACE = pixels  
>
<PARAM NAME = attribute1 VALUE = value1>
<PARAM NAME = attribute2 VALUE = value2>
 ...
Alternate HTML
</APPLET>

For the applet, the loader file would look like the following, and should be located in the same directory as the .class file:

<APPLET
    code=FirstApplet
    height=200
    width=200>
</APPLET>

The code attribute identifies the class name to load. The width and height attributes are self explanatory, stating the desired display size. If the .class file for the applet uses a different base directory than the HTML loader file, you'd need to specify the CODEBASE to tell the browser where to based its search path.

Place the tag in any HTML file and load that file into the browser.

Here's an example method that contains several local inner classes:

NOTE: If you are using Microsoft's virtual machine, Microsoft's Java console might display a NoClassDefFoundError. If you don't have the Java Plug-in installed, and run the applet with Microsoft's VM, it won't load because the .class file format has changed over time. To force the .class file to be compatible with the older Microsoft VM, don't use any features newer than version 1.1.4 and compile with the -target option:

javac -target 1.1 FirstApplet.java

Of course, if you have the Plug-in installed, you won't run into this problem. Just compile the source and tell the browser to load the HTML file and you'll see the applet running. It's that simple.

Pixel
Pixel

Java Bits

Running Threads in Applets

You learned about threads in the October issue of Java Technology Fundamentals. Making use of threads in applets is much the same, with a few concepts to keep in mind.

  • When creating an applet, you extend the Applet class. So, to make use of threads, implement the Runnable interface or define the thread as an inner Thread class.

    public class Example extends Applet implements Runnable

  • Create a new Thread object inside of the applet's start method. (Thread also has a start method, but these are two different methods.)

  • Because you implemented Runnable, you must provide a run method for your class. This method is called by the thread object to perform its actions when the thread starts.

The following applet demonstrates scrolling text that runs on its own thread, allowing you to type into a text field while the text scrolls. If the scrolling text were not on a separate thread, the text would hog the CPU, and you wouldn't be able to type into the text field.

import java.applet.*;
import java.awt.*;

public class ExampleThreads extends Applet implements Runnable
  {
     String text = "An example of text scrolling in its own thread.";
     TextField field;
     Thread thread;
     boolean running;
     
     public void init()
       { //open init
        Font fnt = new Font("Monospaced", Font.BOLD, 26);
        setFont(fnt);
        FontMetrics fm = getFontMetrics(fnt);
        int spaceWidth = fm.charWidth(' ');
        int panelWidth = getSize().width;
        int numSpaces = panelWidth / spaceWidth + 1;
     
        //Add spaces around the text as needed
        for (int i = 0; i < numSpaces; ++i)
          { text = text + ' '; }
        
        field = new TextField("Type Here");
        add(field);
       } //close init
       
     public void start()
      {
        if (thread == null)
         {
           thread = new Thread(this);
           running = true;
           thread.start();
         }
      }
      
     public void run()
      {
        while (running)
         {
           text = text.substring(1, text.length())
                        +text.charAt(0);
           repaint();
           
           try
             {
               Thread.sleep(100);
              }
              
              catch (InterruptedException e)
               {}
              }
             }
             
      public void stop()
       {
         if (thread != null)
          {
            running = false;
            thread = null;
           }
        }
        
      public void paint(Graphics g)
       {
         g.drawString(text, 0, 150);
        
       }
 }

Create the following HTML page to run with appletviewer or in your browser:

<html>
  <head>
  <title>Test Program</title>
  </head>

   <body>
    <applet 
      code="ExampleThreads.class" 
      width="400" 
      height="200">
    </applet>
   </body>
</html>

When the application runs, it should look something like the example below:

See the running applet:

Pixel
Pixel

Making Sense of the Java Class Libraries

Applet, Image, and the MediaTracker Classes

The article above shows how some information is passed to the applet through the HTML page, such as the location of the class file and the height and size of the applet itself. In addition to passing information about the applet itself and its source file, you can also pass it optional parameters using the PARAM tags and getParameter method from the Applet class.

For instance, you might want to display images, or other objects, in your applet. To use images with applets, you must first associate the image with the Image abstract class. Then by passing parameters through the HTML file, you can pass information about how many images you intend to display and their names.

For instance, if you wanted to display four images, you can begin with this:

Image images = new Image[4];

The Image class also has getWidth and getHeight methods that return the size of images in pixels.

The PARAM tag, as shown above, uses the following syntax:

<PARAM NAME = attribute1 VALUE = value1>

So you could create a PARAM tag that tells the applet how many images there are with:

<PARAM NAME = number VALUE=4>

Then go on to name the images in the PARAM tage in the HTML file with:

<PARAM NAME = image1 VALUE=seahorse.jpg>
<PARAM NAME = image2 VALUE=rockfish.jpg>
<PARAM NAME = image3 VALUE=tubesnout.jpg>
<PARAM NAME = image4 VALUE=seabass.jpg>

Which would look like the following example in an HTML file:

You tell the applet to get the parameters with the getParameter method. When you pass a String into the getParameter method, it returns the value of the named parameter in the HTML tag.

For instance:

getParameter("image1");

returns the String seahorse.jpg.

To get the location of applet resources, such as an image, call the getCodeBase method, which returns the URL. In addition you must get the image object itself with the getImage method so that it can be painted on the screen:

getImage(getCodeBase(), "CoLogo.jpg");

To do something more complicated than simply display an image (such as flipping through images) you can use the MediaTracker class to manage and monitor the status of loading images. The MediaTracker class is a utility class used to track the status of a number of media objects.

To construct a MediaTracker object, call the MediaTracker constructor and pass in the Component that draws your images.

For instance:

ImagePanel p = new ImagePanel();
MediaTracker tracker = new MediaTracker(p);

Once you've created the MediaTracker object, have it track a specific image by calling its addImage (Image image, int ID) method. In addition, each image can be assigned a unique identifier. This identifier controls the priority order in which the images are fetched. It can also identify unique subsets of the images that can be waited on independently. Images with a lower ID are loaded in preference to those with a higher ID number.

For example:

tracker.addImage(image, IMAGE_ID);

To find out if the image is loaded and ready to be painted, call one of the following methods:

  • checkAll - Checks to see if all images being tracked by this media tracker have finished loading.
  • checkAll(boolean load) - Checks to see if all images being tracked by this media tracker have finished loading.
  • checkID(int id) - Checks to see if all images tracked by this media tracker that are tagged with the specified identifier have finished loading.
  • statusAll(boolean load) - Calculates and returns the bitwise inclusive OR of the status of all media that are tracked by this media tracker.
  • waitForAll() - Starts loading all images tracked by this media tracker.
  • waitForAll(long ms) - Starts loading all images tracked by this media tracker.

For instance:

int status = tracker.statusALL();
if (status & MediaTracker.COMPLETE)
  System.out.println("Images have been loaded"); 

The MediaTracker class has other methods and constants that are useful for managing images.

Pixel
Pixel

Program Challenge

ImageLoop Applet

You need images for this example. Write an applet cycles through images like a picture album.

  1. Make the applet accept an unlimited number of parameters following the naming pattern of Image1, Image2, Image3, and so forth.
  2. Write parameters to represent the name of an image file.
  3. Make the applet cycle through the image, displaying each like a picture album.

See a possible solution to the Challenge:

Pixel
Pixel

Take Online Quizzes

Applets Quiz

Test what you learned about applets in this issue by taking an online quiz:

Inner Classes Quiz

Pixel
Pixel

For More Information

Writing Applets

Threads in Applets

Creating a Threaded Slide Show Applet

Installation for Conventional Applets (Microsoft Window Only)

Class MediaTracker

Pixel
Pixel

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

Pixel
Pixel
Pixel

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

Pixel
Pixel

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2003 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

Sun, Sun Microsystems, Java, J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Sun Microsystems, Inc.
image
image