How to Create Interactive Web Programs with Java | WebReference

How to Create Interactive Web Programs with Java

current pageTo page 2To page 3To page 4
[next]

How to Create Interactive Web Programs with Java

Excerpted from Sams Teach Yourself Programming with Java in 24 Hours by Rogers Cadenhead. ISBN 0672328445, Copyright © 2006. Used with the permission of Sams Publishing.

Now that Java has made the transition from a child prodigy to an established language, it is being used for all kinds of large-scale business software and other applications. However, for some people, the core appeal of the language remains a type of program that Java made possible: the applet.

Applets are programs designed to run as part of a World Wide Web page. When a Java applet is encountered on a page, it is downloaded to the user's computer and begins running.

During this hour you'll be introduced to applet programming and Java Web Start, a way to install and run Java software from within a web browser.

Programming applets with Java is much different from creating applications with Java. Because applets must be downloaded from a page each time they are run, they're smaller than most applications to reduce download time. Also, because applets run on the computer of the person using the applet, they have numerous security restrictions in place to prevent malicious or damaging code from being run.

The following topics will be covered:

  • Displaying information in an applet

  • Stopping and starting an applet

  • Putting an applet on a web page

  • Customizing an applet with parameters on a web page

  • Receiving parameters in an applet

  • Running applets with the Java Plug-in

Standard Applet Methods

The first step in the creation of an applet is to make it a subclass of JApplet, a class that's part of the Swing package, javax.swing. An applet is treated as a visual window inside a web page, so JApplet is part of Swing alongside clickable buttons, scrollbars, and other components of a program's user interface.

JApplet is a subclass of Applet, a class in the java.applet package. Being part of this hierarchy enables the applets you write to use all the behavior and attributes they need to be run as part of a web page. Before you begin writing any other statements in your applets, they will be able to interact with a web browser, load and unload themselves, redraw their window in response to changes in the browser window, and handle other necessary tasks.

In applications, programs begin running with the first statement inside the main()block statement and end with the last closing bracket (}) that closes out the block. There is no main() method in a Java applet, so there is no set starting place for the program. Instead, an applet has a group of standard methods that are handled in response to specific events as the applet runs.

The following are the events that could prompt one of the applet methods to be handled:

  • The program is loaded for the first time, which causes the applet's init() and start() methods to be called.

  • Something happens that requires the applet window to be redisplayed, which causes the applet's paint() method to be called.

  • The program is stopped by the browser, which calls the applet's stop() method.

  • The program restarts after a stop, which calls the start() method.

  • The program is unloaded as it finishes running, which calls the destroy()method.

The following is an example of a bare-bones applet:

public class Skeleton extends javax.swing.JApplet {
    // program will go here
}

Unlike applications, applet class files must be public because the JApplet class is also public. (If your applet uses other class files of your own creation, they do not have to be declared public.)

Your applet's class inherits all the methods that are handled automatically when needed: init(), paint(), start(), stop(), and destroy(). However, none of these methods do anything. If you want something to happen in an applet, you have to override these methods with new versions in your applet program.

Painting an Applet Window

The paint() method is used to display text, shapes, and graphics within the applet window. Whenever something needs to be displayed or redisplayed on the applet window, the paint() method handles the task. You also can force paint() to be handled with the following statement in any method of an applet:

repaint();

Aside from the use of repaint(), the main time the paint() method is handled is when something changes in the browser or the operating system running the browser. For example, if a user minimizes a web page containing an applet, the paint() method will be called to redisplay everything that was onscreen in the applet when the applet is later restored to full size.

Unlike the other methods you will be learning about during this hour, paint()takes an argument. The following is an example of a simple paint() method:

public void paint(Graphics screen) {
    Graphics2D screen2D = (Graphics2D)screen;
        // display statements go here
}

The argument sent to the paint() method is a Graphics object. The Graphics class of objects represents an environment in which something can be displayed, such as an applet window. As you did with Swing programs, you may cast this to a Graphics2D object to employ more sophisticated graphical features.

Later this hour, you'll learn about drawString(), a method for the display of text that's available in both the Graphics and Graphics2D classes.

If you are using a Graphics or Graphics2D object in your applet, you have to add the following import statements before the class statement at the beginning of the source file:

import java.awt.Graphics;
import java.awt.Graphics2D;

Initializing an Applet

The init() method is handled once—and only once—when the applet is run. As a result, it's an ideal place to set up values for any objects and variables that are needed for the applet to run successfully. This method is also a good place to set up fonts, colors, and the screen's background color. Here's an example:

public void init() {
FlowLayout flo = new FlowLayout();
    setLayout(flo);
    JButton run = new JButton("Run");
    add(run);
}

If you are going to use a variable in other methods, it should not be created inside an init() method because it will only exist within the scope of that method.

For example, if you create an integer variable called displayRate inside the init()method and try to use it in the paint() method, you'll get an error when you attempt to compile the program. Create any variables you need to use throughout a class as object variables right after the class statement and before any methods.

Starting and Stopping an Applet

At any point when the applet program starts running, the start() method will be handled. When a program first begins, the init() method is followed by the start() method. After that, in many instances there will never be a cause for the start() method to be handled again. In order for start() to be handled a second time or more, the applet has to stop execution at some point.

The stop() method is called when an applet stops execution. This event can occur when a user leaves the web page containing the applet and continues to another page. It also can occur when the stop() method is called directly in a program.

Destroying an Applet

The destroy() method is an opposite of sorts to the init() method. It is handled just before an applet completely closes down and completes running.

This method is used when something has been changed during a program that should be restored to its original state. It's another method you'll use more often with animation than with other types of programs.

Putting an Applet on a Web Page

Applets are placed on a web page in the same way that anything unusual is put on a page: HTML markup tags describe the applet, which a web browser loads along with the other parts of the page. If you have used HTML to create a web page, you know that it's a way to combine formatted text, images, sound, and other elements together. HTML uses special commands called tags that are surrounded by marks, including img for the display of images, p for the insertion of a paragraph mark, and <center> to center the text that follows until a </center> tag is reached.

The performance of some of these HTML tags can be affected by attributes that determine how they function. For example, src is an attribute of the img tag, and it provides the name of the image file that should be displayed. The following is an example of an img tag:

<IMG SRC=”graduation.jpg”>

One way to place applets on a web page is by using an applet tag and several attributes. The following is an example of the HTML required to put an applet on a page:

<applet code=”StripYahtzee.class” codebase=”javadir” height=”300” width=”400”>
Sorry, no dice ... this requires a Java-enabled browser.
</applet>

The code attribute identifies the name of the applet's class file. If more than one class file is being used with an applet, code should refer to the main class file that is a subclass of the JApplet class.

If there is no code attribute, all files associated with the applet should be in the same folder as the web page that loads the program. codebase should contain a reference to the folder or subfolder where the applet and any related files can be found. In the preceding example, codebase indicates that the StripYahtzee applet can be found in the javadir subfolder.

The height and width attributes designate the exact size of the applet window on the web page. It must be big enough to handle the things you are displaying in your applet.

In between the opening <applet> tag and the closing </applet> tag, you can provide an alternate of some kind for web users whose browser software cannot run Java programs (less than two percent of all web users run browsers that fall into this group).

In the preceding example, the text “Sorry, no dice…this requires a Java-enabled browser” is displayed in place of the applet on a browser such as Lynx, which does not support Java. You can put instructions here on how to download a Java-enabled browser. You also can include hyperlinks and other HTML elements.

Another useful attribute, align, designates how an applet will be displayed in relation to the surrounding material on the page, including text and graphics. The value align=”left” lines up the applet to the left of adjacent page elements and align=”right” lines it up to the right.

A Sample Applet

This hour's first project is an applet that displays the string "Saluton mondo!", the traditional Esperanto greeting that is becoming more traditional by the hour. You'll take a look at how applets are structured by re-creating the Saluton application from Hour 2, "Writing Your First Program," as a program that can run on a web page.

Load your word processor and create a new file called SalutonApplet.java. Enter the text of Listing 17.1 into the file and save it when you're done.

This applet does not need to use the start(), stop(), or destroy() methods, so they are not included in the program. Compile the program with the javac compiler tool, if you're an JDK user, or another tool.

Created: March 27, 2003
Revised: February 13, 2006

URL: http://webreference.com/programming/java_24/1