Overview of Applets

Table of contents:

This section discusses the parts of an applet. If you haven't yet compiled an applet and included it in an HTML page, you might want to follow the step-by-step instructions found in the chapter Getting Started (page 1).

Every applet is implemented by creating a subclass of the Applet class. Figure 112 shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what an applet can do and how it does it, as you'll see on the next few pages.

Figure 112. The Applet class inherits much of its functionality from its superclasses.

graphics/apbfig01.gif

A Simple Applet

graphics/intfig04.gif

Following is the source code for an applet called Simple. [1] The Simple applet displays a descriptive string whenever it encounters a milestonea major event in an applet's life cycle, such as when the user first visits the page that contains the applet. The following pages build on the Simple applet to illustrate concepts that are common to many applets.

[1] Simple.java is included on the CD and is available online. See Code Samples (page 463).

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

public class Simple extends Applet { 
 StringBuffer buffer; 

 public void init() { 
 buffer = new StringBuffer(); 
 addItem("initializing... "); 
 } 

 public void start() { 
 addItem("starting... "); 
 } 

 public void stop() { 
 addItem("stopping... "); 
 } 

 public void destroy() { 
 addItem("preparing for unloading..."); 
 } 

 void addItem(String newWord) { 
 System.out.println(newWord); 
 buffer.append(newWord); 
 repaint(); 
 } 

 public void paint(Graphics g) { 
 //Draw a Rectangle around the applet's display area. 
 g.drawRect(0, 0, 
 getSize().width - 1, 
 getSize().height - 1); 

 //Draw the current string inside the rectangle. 
 g.drawString(buffer.toString(), 5, 15); 
 } 
} 

The Life Cycle of an Applet

Here is a picture of the Simple applet.

http://java.sun.com/docs/books/tutorial/applet/overview/lifeCycle.html

graphics/apbfig02.gif

Loading the Applet

The initializing... starting... text you see in the previous applet is the result of the applet's being loaded. When an applet is loaded, here's what happens.

  • An instance of the applet's controlling class (an Applet subclass) is created.
  • The applet initializes itself.
  • The applet starts running.

Note

Some browsers let you load serialized appletsapplets that have been saved while running. When a serialized applet is loaded, it doesn't initialize itself; it simply starts running.

 

Leaving and Returning to the Applet's Page

When the user leaves the pagefor example, to go to another pagethe applet has the option of stopping itself. When the user returns to the page, the applet can start itself again. The same sequence occurs when the user iconifies and then deiconifies the window that contains the applet. (Alternative terms for "iconify" are miniaturize, minimize, and close.)

Try This

Visit the online version of this tutorial at this URL: http://java.sun.com/docs/books/tutorial/applet/overview/lifeCycle.html. Leave and then return to this page. You'll see stopping... added to the applet output, as the applet is given the chance to stop itself. You'll also see starting... when the applet is told to start itself again. Next, iconify the window that contains the online version of this section, and then open it again. Many window systems provide a title bar button that lets you iconify the window. You should see stopping... then preparing for unloading..., initializing..., and starting... added to the applet output. Note that the exact text displayed will depend on your browser and platform.

 

Reloading the Applet

Some browsers let the user reload applets, a process that consists of unloading the applet and then loading it again. Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup so that the applet can release any resources it holds. After that, the applet is unloaded and then loaded again.

Try This

Try to reload the applet. (Shift-Reload in Netscape Navigator or Shift-Refresh in Internet Explorer might reload the applet.) Look at the standard output in the lower-left-hand corner of the browser to see what happens. You should see stopping... and preparing for unloading... when the applet is unloaded. You can't see this in the applet GUI, because the applet is unloaded before the text can be displayed. When the applet is reloaded, you should see initializing... and starting..., just like when you loaded the applet for the first time. However, the only way to make sure the browser reloaded the applet is to change the applet and look for a change in a visible way; for example, change the string to make sure you unloaded the applet.

 

Quitting the Browser

When the user quits the browser, the applet has the chance to stop itself and to do final cleanup before the browser exits.

Summary

An applet can react to milestones in the following ways.

  • It can initialize itself.
  • It can start running.
  • It can stop running.
  • It can perform a final cleanup, in preparation for being unloaded.

The next section describes the four applet methods that correspond to these four reactions.

Methods for Milestones

The Simple applet, like every other applet, contains a subclass of the Applet class. The Simple class overrides four Applet methods so that it can respond to major events:

public class Simple extends Applet { 
 . . . 
 public void init() { . . . } 
 public void start() { . . . } 
 public void stop() { . . . } 
 public void destroy() { . . . } 
 . . . 
} 

init

To initialize the applet each time it is loaded or reloaded

start

To start the applet's execution, such as when the applet is loaded or when the user revisits a page that contains the applet

stop

To stop the applet's execution, such as when the user leaves the applet's page or quits the browser

destroy

To perform a final cleanup in preparation for unloading

Not every applet needs to override every one of these methods. Some simple applets override none of them. For example, the HelloWorld applet discussed in the chapter Getting Started (page 1) doesn't override any of these methods, because it doesn't do anything except draw itself. It just displays a string once, using its paint method. (The paint method is described in the next section.)

The init method is useful for one-time initialization that doesn't take very long. In general, this method should contain the code that you would normally put into a constructor. An applet usually shouldn't have constructors, because it isn't guaranteed to have a full environment until its init method is called. For example, the Applet image-loading methods simply don't work inside a constructor. The init method, on the other hand, is a great place to call the image-loading methods, because the methods return quickly.

Note

When a browser loads a serialized applet, it does not invoke the applet's init method. The reason: The init method was presumably executed before the applet was serialized. See the section Object Serialization (page 334) for more information.

Every applet that does something after initialization (except in direct response to user actions) must override the start method. The start method either performs the applet's work or, more likely, starts up one or more threads to perform the work. You can read more about threads later in this appendix in the section Threads in AWT Applets (page 449). [1] The next section talks more about handling the events that represent user actions.

[1] Threads are also covered in the chapter Threads: Doing Two or More Tasks at Once (page 269).

Most applets that override start should also override the stop method, which should suspend the applet's execution so that it doesn't take up system resources when the user isn't viewing the applet's page. For example, an applet that displays animation should stop drawing the animation when the user isn't viewing it in the current browser window.

Many applets don't need to override the destroy method, because their stop methods (called before destroy) do everything necessary to shut down the applet's execution. However, destroy is available for applets that need to release additional resources.

The init, start, stop, and destroy methods are discussed and used throughout this tutorial. For more information, you can also refer to the Applet API documentation for JDK 1.1. [2]

[2] http://java.sun.com/products/jdk/1.1/api/java.applet.Applet.html

Methods for Drawing and Event Handling

The Simple applet defines its on-screen appearance by overriding the paint method:

class Simple extends Applet { 
 . . . 
 public void paint(Graphics g) { . . . } 
 . . . 
} 

The paint method is one of two display methods that applets can override:

paint

The basic display method. Many applets implement the paint method to draw the applet's representation within a browser window.

update

A method that you can use with paint to improve drawing performance.

Applets inherit their paint and update methods from the Applet class, which inherits them from the Abstract Window Toolkit (AWT) Component class. Applets inherit event-related functionality and methods from the Component class. The architecture of the event system is discussed in the section Handling Events (page 358) in Chapter 10. The Component class defines several methods, such as addMouseListener and addKeyListener, that register objects to be automatically notified about various kinds of events. To be registered, an object must implement the appropriate interface.

For example, for an object to be registered as a mouse listener on an applet, that object must implement the MouseListener interface. Once registered, that listener object will be notified every time the user clicks in the applet's drawing area. This notification comes in the form of calling the listener's mouseClicked method. The listener can be the Applet object itself or any other object. The only requirement is that the object implement the correct listener interface.

graphics/intfig04.gif

Adding the following boldface code to the Simple applet registers it as a mouse listener and makes it respond to mouse clicks: [1]

[1] SimpleClick.java is included on the CD and is available online. See Code Samples (page 463).

import java.awt.event.MouseListener; 
import java.awt.event.MouseEvent; 
. . . 
public class Simple extends Applet 
 implements MouseListener { 
 . . . 
 public void init() { 
 addMouseListener(this); 
 . . . 
 } 
 . . . 
 public void mouseClicked(MouseEvent event) { 
 addItem("click!... "); 
 } 
. . . 
} 

Note

To keep the example simple, we've left out a few empty method definitions.

Following is the resulting output from the applet. When you click within its rectangle, it displays the word click!....

http://java.sun.com/docs/books/tutorial/applet/overview/componentMethods.html

graphics/apbfig03.gif

Methods for Adding UI Components

The Simple applet's display code (implemented in its paint method) is flawed: It doesn't support scrolling. Once the text it displays reaches the end of the display rectangle, you can't see any new text.

Here's an example of the problem:

graphics/apbfig04.gif

The simplest cure for this problem is to use a premade user interface (UI) component that has the correct behavior. The Java platform supplies many UI components, including buttons, text fields, and menus. Remember that if you're designing an applet to run on most Web browsers without the Java Plug-in, you'll want to build an applet with AWT components. The section AWT Components (page 419) gives an overview of the major AWT components. Chapter 10 gave an overview of the Swing UI components, and the last section in this appendix will discuss how to make Swing applets.

Methods for Using UI Components in Applets

Because the Applet class inherits from the AWT Container class, it's easy to add components to applets. Here are some of the Container methods an applet can use:

add

Adds the specified Component to the applet.

remove

Removes the specified Component from the applet.

setLayout

Sets the applet's layout manager, which controls the positions and sizes of the components in the applet.

Adding an Uneditable Text Field to the Simple Applet

graphics/intfig04.gif

Using the TextField class, you can add a scrolling, uneditable text field to the Simple applet. [1] The changes are in boldface in the following code:

[1] ScrollingSimple.java is included on the CD and is available online. See Code Samples (page 463).

//Importing java.awt.Graphics is no longer necessary 
//since this applet no longer implements the paint method. 
. . . 
import java.awt.TextField; 
public class Simple extends Applet { 

 //Instead of using a StringBuffer, use a TextField: 
 TextField field; 

 public void init() { 
 //Create the text field and make it uneditable. 
 field = new TextField(); 
 field.setEditable(false); 

 //Set the layout manager so that the text field will 
 //be as wide as possible. 
 setLayout(new java.awt.GridLayout(1,0)); 
 //Add the text field to the applet. 
 add(field); 

 addItem("initializing... "); 
 } 
 . . . 
 void addItem(String newWord) { 
 //This used to append the string to the StringBuffer; 
 //now it appends it to the TextField. 
 String t = field.getText(); 
 System.out.println(newWord); 
 field.setText(t + newWord); 
 } 

 //The paint method is no longer necessary, 
 //since the TextField paints itself automatically. 

The revised init method creates an uneditable text field, a TextField instance. This method also sets the applet's layout manager to one that makes the text field as wide as pos-sible and then adds the text field to the applet. You can read about layout managers in the section Layout Management (page 375) in Chapter 10.

Following is the output of the resulting applet. By dragging the mouse, you can scroll backward or forward to see all the messages that have been displayed.

http://java.sun.com/docs/books/tutorial/applet/overview/containerMethods.html

graphics/apbfig05.gif

What Applets Can and Cannot Do

When you write an applet, you can, in theory, use any of the API in the Java platform. In practice, however, applets are limited in a couple of ways.

  • An applet can use only the API supported by the browser in which it runs. For example, unless a browser supports the API defined in JDK 1.1, no applet that uses 1.1 API can run in that browser.
  • An untrusted applet can't perform operations that might pose a security threat. For example, an untrusted applet cannot read or write files on the computer on which it is executing. See the section Security Restrictions (page 442) for more information.

Despite these restrictions, applets have access to a wide range of functionality. For example, applets can communicate with certain other applets running in the same browser. Applets can also request that the browser display a particular URL. See the section Taking Advantage of the Applet API (page 423) for information about the API that's reserved just for applets. See the section Practical Considerations of Writing Applets (page 442) for information about the other API applets commonly use.

Test Driving an Applet

Once you've written some code for your applet, you'll want to run your applet to test it. To run an applet, you first need to add the applet to an HTML page, using the tag. You then specify the URL of the HTML page to your Java-enabled browser.

Note

Because you can't always rely on browsers to reload your applet's classes, you might want to use a quick-starting tool, such as the Applet Viewer, for most of your applet testing. Every time you change your applet, restart the Applet Viewer to make sure that it loads all the latest classes.

 

Here's the simplest form of the tag:

anInt HEIGHT=anInt> 

This tag tells the browser to load the applet whose Applet subclass is named AppletSub class . Figure 113 shows where the applet class file must be, relative to the HTML document that contains the tag. As Figure 113 shows, unless the applet is declared to be in a package, its class file should be in the same directory as the HTML file that has the tag.

Figure 113. An applet's class files live under the same directory as the HTML file that includes the applet.

graphics/apbfig06.gif

When it encounters an tag, a Java-enabled browser reserves a display area of the specified width and height for the applet, loads the bytecodes for the specified Applet subclass, creates an instance of the subclass, and then calls the instance's init and start methods.

The tag has many options that you can use to customize your applet's execution. For example, you can put your applet's files into an archive. You can also specify parameters to be passed to the applet. These options are described in the section Using theTag (page 438).

Summary

This section gave you lots of informationalmost everything you need to know to start writing an applet based on the 1.0 and 1.1 JDK. So let's review the big picture: To write an applet, you must create a subclass of the java.applet Applet class. In your Applet subclass, you must implement at least one of the following methods: init, start, and paint. The methods init and start, along with stop and destroy, are called when major events (milestones) occur in the applet's life cycle. The paint method is called when the applet needs to draw itself to the screen.

The Applet class extends the Panel class, which extends the Container class, which extends the Component class. From Component, an applet inherits the ability to draw and to handle events. From Container, an applet inherits the ability to include other components and to have a layout manager control the size and the position of those components. From Applet, an applet inherits several capabilities, including the ability to respond to milestones. The next section tells you more about what the Applet class provides.

You include applets in HTML pages by using the tag. When a browser user visits a page that contains an applet, the following sequence occurs.

  1. The browser finds the class file (which contains Java bytecodes) for the applet's Applet subclass.
  2. The browser brings the Applet subclass bytecodes over the network to the user's computer.
  3. The browser creates an instance of the Applet subclass. (When we refer to an applet, we're generally referring to this instance.)
  4. The browser calls the applet's init method. This method performs any initialization that is required.
  5. The browser calls the applet's start method. This method often starts a thread to perform the applet's duties.

An applet's Applet subclass is its main, controlling class, but applets can use other classes as well. These other classes can be either local to the browser (provided as part of the Java platform) or custom classes that you supply. When the applet tries to use a class for the first time, the browser tries to find the class on the host that is running the browser and applet. If the browser cannot find the class there, it looks for the class in the same place from which the applet's Applet subclass came. When the browser finds the class, it loads the bytecodes for the class (over the network, if necessary) and continues executing the applet.

Loading executable code over the network is a classic security risk. For Java applets, some of this risk is reduced because the Java language is designed to be safefor example, it doesn't allow pointers to random memory. In addition, browsers enforce security by imposing restrictions on untrusted applets.

AWT Components

Getting Started

Object-Oriented Programming Concepts

Language Basics

Object Basics and Simple Data Objects

Classes and Inheritance

Interfaces and Packages

Handling Errors Using Exceptions

Threads: Doing Two or More Tasks at Once

I/O: Reading and Writing

User Interfaces That Swing

Appendix A. Common Problems and Their Solutions

Appendix B. Internet-Ready Applets

Appendix C. Collections

Appendix D. Deprecated Thread Methods

Appendix E. Reference



The Java Tutorial(c) A Short Course on the Basics
The Java Tutorial: A Short Course on the Basics, 4th Edition
ISBN: 0321334205
EAN: 2147483647
Year: 2002
Pages: 125

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net