- Special Edition Using Java, 2nd Edition -

Chapter 15

Writing an Applet


by Clayton Walnum

Now that you've learned the Java language, you can apply your new knowledge toward writing Java applets, which are small programs that can be added to a Web page. Because of their ability to add real pizzazz to Web sites, Java applets have become the latest Internet rage. However, before you actually get to work on writing your own applets, you need to know a little background, such as the difference between an applet and a standalone application, as well as how to add an applet to an HTML document.

Because you're interested in writing Java applets, you're probably already pretty familiar with using HTML (Hypertext Markup Language) to create Web pages. If not, you should pick up a book on HTML and get some idea of how that markup language works. Even if you're an HTML expert, though, you may not have seen the HTML extension that Sun Microsystems created to support Java applets in Web pages. In this chapter, then, you not only get a chance to see your own Java applets up and running, but you also learn how to add them to your Web pages.

Applets Reviewed

As you now know, Java can be used to create two types of programs: applets and standalone applications. An applet is simply part of a Web page, like an image or a line of text. Just as a browser takes care of displaying an image referenced in an HTML document, a Java-enabled browser locates and runs an applet. When your Java-capable Web browser loads the HTML document, the Java applet is also loaded and executed. It doesn't matter whether or not the applet is currently available on your hard drive. If necessary, your Web browser automatically downloads the applet before running it. (See Chapter 1, "What Java Can Do For You," for more information.

It is an applet's ability to hitch a ride on the Information Superhighway that makes it so unique. In fact, applets are really the first step towards making the Internet a true extension of your computer's local storage system. When you view a Web page containing applets, those applets may be coming to you from just about anywhere on the Web—from the office down the street or from a software distributor in Hong Kong.

If a required applet is not located on your system, it can be downloaded automatically to your system and then run. To the user, this exchange of applets over the Internet is mostly transparent. All the user knows is that she's looking at a page that contains a game of TicTacToe, an animated image, or some other Java-based content.
 

There's a client/server relationship between a browser that wants to display an applet and the system that can supply the applet. The client is a computer that requires services from another system; the server is the computer that provides those services. In the case of a Java applet, the client is the computer that's trying to display an HTML document that contains a reference to an applet. The server is the computer system that uploads the applet to the client, thereby allowing the client to use the applet.

You may have heard horror stories about people who have downloaded programs from the Internet only to find, after running the program, that it has infected their system with a virus or otherwise wreaked havoc with their computer. Therefore, you may be reluctant to jump on the applet bandwagon. After all, with so many applets flying around the Internet, trouble could rear its ugly head like a demon from a Clive Barker novel.

The truth, however, is that Java applets are a secure way to transmit programs on the Internet. This is because the Java interpreter will not allow an applet to run until the interpreter has confirmed that the applet's byte-code has not been corrupted or changed in some way (see fig. 15.1). Moreover, the interpreter determines whether the byte-code representation of the applet sticks to all of Java's rules. For example, a Java applet can never use a pointer to gain access to portions of computer memory for which it doesn't have access. The bottom line is that, not only are Java applets secure, they are virtually guaranteed not to crash the system.


FIG. 15.1

Applets are verified before they are run.

By using applets, you can do everything from adding animated graphics to your Web pages to creating complete games and utilities that can be executed over the Internet.
 

Some applets that have already been created with Java include Bar Chart, which embeds a configurable bar chart in an HTML document; Crossword Puzzle, which enables users to solve a crossword puzzle on the Web; and LED Sign, which presents a scrolling, computerized message to viewers of the Web page within which the applet is embedded. Figure 15.2 shows a spreadsheet applet running in Netscape Navigator 2.0.


FIG. 15.2

Some applets, such as this small spreadsheet program, provide sophisticated content to Web pages.

Applets Versus Applications

Although most Java programmers are excited by the ability to create applets, Java can also be used to create standalone applications—that is, applications that don't need to be embedded in an HTML document. The most well-known application is the HotJava Web browser. This basic browser is completely written in the Java language, showing how Java handles not only normal programming tasks such as looping and evaluating mathematical expressions, but also how it can handle the complexities of telecommunications programming.

Whereas an applet can be transmitted automatically over the Internet, a Java standalone application resides on your local hard drive. In fact, a Java application is just like any other application you have installed on your system. The only difference is that it was written with Java rather than with some other computer language like C++.

To run a Java application that you've written, you must invoke the Java interpreter, which reads in the application's byte-code file and executes it. Because the Java interpreter currently runs from a command line, you must start a Java application from the command line, even if the application is windowed. In the case of a Java Windows application, even though it is started from DOS, the application appears under Windows just as any other Windows application would.

Another big difference between applets and standalone applications is the way they deal with security issues. An applet's ability to access files, for example, is controlled by environment variables that the user sets with his Web browser. An applet is not allowed to access any files or directories for which it doesn't have permission. For this reason, most applets don't deal with files in any way, because they can never be sure exactly what kind of disk access they'll be allowed.

Standalone applications, on the other hand, are not constrained by the tight security applied to applets. They can access files normally, just like any other application. Tight security is not needed for standalone applications because they are not transmitted to you unknowingly over the Internet. This is unlike applets, which are transmitted to your system automatically as part of a Web page. The applets security restraints prevent the server (the system that sent you the applet) from accessing information on your system.

Adding an Applet to an HTML Document

Now that you know a little about applets, it's time to learn how to add them to your Web pages. If you've created Web pages before, you know that you use HTML to create a template for the page. The commands in the template tell a Web browser how to display the Web page. When Sun Microsystems developed Java, they also had to come up with an extension to HTML that would enable Web pages to contain Java applets. That extension is the <applet> tag, which Sun Microsystems defines as shown in listing 15.1.

Listing 15.1 LST15_01.TXT: The <applet> tag.

<applet attributes>
parameters
alternate-content
</applet>

In the preceding tag, the text in normal characters is typed literally; the text shown in italics is replaced by whatever is appropriate for the applet you're including in the document. As you can see, the <applet> tag is similar to other HTML tags with which you may be familiar. For example, the tag starts with <applet attributes> and ends with </applet>, which is not unlike the format of other HTML tags. The first and last lines are required. Other lines in the tag are optional.

The attributes section of the <applet> tag contains important information about the tag, including the associated .class file and the applet's width and height. The last line tells the browser that it has reached the end of the tag. You can load and run the TicTacToe applet, for example, with the <applet> tag shown in listing 15.2.

Listing 15.2 LST15_02.TXT: A tag for loading and running TicTacToe.

<applet
code=TicTacToe.class
width=120
height=120>
</applet>

In the preceding example, the code attribute is the name of the .class file for the applet. If you remember, the .CLASS file holds the applet's byte-code representation, which can be run by the Java interpreter. The width and height attributes control the size of the applet. The TicTacToe tag is the simplest <applet> tag you can write. That is, the code, width, and height attributes are all required, as is the final </applet> line.

Optional Attributes for Applets

There are several optional attributes you can use with the <applet> tag. The first is codebase, which specifies the applet's base folder or URL (Uniform Resource Locator). This folder or URL is used in combination with the file specified in the code attribute to find the applet's code. In the case of a folder, the codebase attribute is relative to the location of the HTML document containing the applet's tag. In listing 15.2, because the codebase attribute is missing, the Web browser looks for the applet's files in the same folder as the HTML document. The <applet> tag in listing 15.3 looks like listing 15.2 when using the codebase attribute. (Don't try to run this HTML code, as it's only an example of the attribute's format and may not run.)

Listing 15.3 LST15_03.TXT: Using the codebase attribute.

<applet
codebase=tictactoe
code=TicTacToe.class
width=120
height=120>
</applet>

The preceding tag tells the browser that the TicTacToe.class file is located in a folder called TICTACTOE. This folder must be on the same level in the directory tree as the HTML file. That is, if the HTML file is in the folder JAVA\DEMO, then the path for the .CLASS file should be JAVA\DEMO\TICTACTOE\TICTACTOE.CLASS. You can also use a URL, such as http://www.provider.com/my_pages/tictactoe, for the codebase attribute. This causes the applet to be loaded from the specified site.

Other optional attributes you can use with the <applet> tag are alt, , name, align, hspace, and vspace. The alt attribute enables you to specify text that is displayed by text-only browsers, whereas the name attribute gives the applet a symbolic name that's used to reference the applet (used when you need to communicate between applets).

The align, hspace, and vspace attributes all work together to position the applet within the text flow of the HTML document. These attributes work exactly as they do with the <img> tag that's used to display images in Web pages. The align attribute can be one of these values: left, right, middle, absmiddle, bottom, absbottom, baseline, top, or texttop. The hspace and vspace attributes control the amount of white space around the applet when align is set to left or right.

Listing 15.4 shows the script for a simple Web page using the <applet> tag. Figure 15.3 shows Netscape Navigator 2.0 displaying the page.

If you try this code, the applet area is blank because you have not created the TicTacToe.class. You write some interesting Java applets later in this chapter.
 

Listing 15.4 LST15_04.TXT: A simple HTML document using the <applet> tag.

<title>TicTacToe</title>
<hr>
This is a bunch of text whose sole purpose is to demonstrate
the placement
<applet
codebase=TicTacToe
code=TicTacToe.class
width=120
height=120
alt="This is the TicTacToe applet."
name=TicTacToe
align=middle>
</applet>
of the TicTacToe applet within the text flow of an HTML document.

<hr>

FIG. 15.3

This is the Web page created by listing 15.4.

To load an HTML document into Netscape Navigator 2.0, choose File, Open File or press Ctrl+O. Then select the file in the dialog box that appears.
 

Non-Java Browsers

You may wonder what happens when a browser that's not Java-compatible finds an applet in an HTML document. In this case, as is standard behavior for browsers, the non-Java browser simply ignores the tags it doesn't recognize. However, you may want to provide a more user-friendly response to users who are trying to view your applets with non-Java browsers. You can do this easily by placing alternate content right before the ending </applet> tag. Listing 15.5, for example, shows the HTML script for running the TicTacToe applet with alternate content for browsers that don't support Java.

Listing 15.5 LST15_05.TXT: Supplying alternate content for TicTacToe.

<applet
code=TicTacToe.class
width=120
height=120>
<b>If you had a Java-compatible browser,
you'd be playing TicTacToe right now!</b>
</applet>

The alternate content you provide can comprise any standard HTML commands and is ignored by Java-compatible browsers. That is, the alternate content appears only in non-Java browsers.

The Simplest Java Applet

At last, you're about to write your first Java applet. The Java programming language and libraries enable you to create applets that are as simple or as complex as you like. In fact, you can write the simplest Java applet in only a few lines of code, as shown in listing 15.6.

Listing 15.6 MyApplet.java: The simplest Java applet.

import java.applet.*;
public class MyApplet extends Applet
{
}

The first line of listing 15.6 tells the Java compiler that this applet will be using some or all of the classes defined in the applet package (the asterisk acts as a wild card, just as in DOS file names). All of the basic capabilities of an applet are provided for in these classes, which is why you can create a usable applet with so few lines of code.

The second line of code declares a new class called MyApplet. This new class is declared as public so that the class can be accessed when the applet is run in a Web browser or in the Appletviewer application. If you fail to declare the applet class as public, the code compiles fine, but the applet refuses to run. In other words, all applet classes must be public.

As you can see, you take advantage of object-oriented programming (OOP) inheritance to declare your applet class by subclassing Java's Applet class. This inheritance works exactly the same as when you create your own class hierarchies. The only difference is that Applet is a class that's included with the Java Developer's Kit (JDK), rather than a class you created yourself. For more information on inheritance, check out Chapter 12, "Classes in Depth."
 

You can actually compile the applet shown in listing 15.6. When you do, you' have the MyApplet.class file, which is the byte-code file that can be executed by the Java system. To run the applet, just create an HTML document like the one shown in listing 15.7. If you were to run the MyApplet applet, however, you wouldn't see anything much in Appletviewer or in your Web browser. In the next section, you create an applet that actually does something.

Listing 15.7 MYAPPLET.HTML: MyApplet's HTML document.

<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet
code="MyApplet.class"
width=250
height=250
name="MyApplet">
</applet>

An Applet That Draws on the Screen

Although most applets are fairly simple, there are a few things you need to know how to do in order to write your own applets. First, you must know how to draw your applet's display. This means using Java's Graphics class, as well as learning how to arrange controls such as text boxes and buttons into a logical order.

Another important thing you must know is how to handle events. Just like any other program running in a windowed environment, Java applets receive a flood of messages from the system and the user. Your applet must handle the messages that are appropriate to the task it must complete.

For example, responding to mouse movement isn't something you have to do often in your applets. Still, it's a handy tool to have under your belt. You might, for example, need to track mouse movement when writing a game applet that uses the mouse as input. A more common use is in graphics programs that enable you to draw on the screen. Listing 15.8 is just such an applet. Listing 15.9 shows the HTML document that loads and runs the applet.

When you run DrawApplet with Appletviewer, you see a blank window. Click the mouse in the window to choose a starting point and then move the mouse around the window. Wherever the mouse pointer goes, it leaves a black line behind (see fig. 15.4). Although this is a very simple drawing program, it gives you some idea of how you might use a mouse to accomplish other similar tasks.

Listing 15.8 DrawApplet.java: The DrawApplet applet.

import java.awt.*;
import java.applet.*;
public class DrawApplet extends Applet
{
Point startPoint;
Point points[];
int numPoints;
boolean drawing;
public void init()
{
startPoint = new Point(0, 0);
points = new Point[1000];
numPoints = 0;
drawing = false;
resize(400, 300);
}
public void paint(Graphics g)
{
int oldX = startPoint.x;
int oldY = startPoint.y;
for (int x=0; x<numPoints; ++x)
{
g.drawLine(oldX, oldY, points[x].x, points[x].y);
oldX = points[x].x;
oldY = points[x].y;
}
}
public boolean mouseDown(Event evt, int x, int y)
{
if (!drawing)
{
drawing = true;
startPoint.x = x;
startPoint.y = y;
}
else
drawing = false;
return true;
}
public boolean mouseMove(Event evt, int x, int y)
{
if ((drawing) && (numPoints < 1000))
{
points[numPoints] = new Point(x, y);
++numPoints;
repaint();
}
return true;
}
}

Listing 15.9 DRAWAPPLET.HTML: DrawApplet's HTML document.

<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet
code="DrawApplet.class"
width=400
height=400
name="DrawApplet">
</applet>

FIG. 15.4

The DrawApplet applet responds to mouse-movement and mouse-click messages.

Understanding the DrawApplet Applet

Now that you're finished drawing masterpieces with DrawApplet, it's time to see how the applet works. The first two lines of source code tell Java that the applet uses the classes in the awt and applet packages:

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

The awt (Abstract Windowing Toolkit) package contains classes for drawing displays in a windowed environment. These classes give an applet access to methods for drawing on the screen, responding to events, manipulating controls like buttons and menus, and much more. The applet package contains the classes needed to create the basic applet.

The next line in the program derives DrawApplet from the Applet class, which Java defines in the applet package:

public class DrawApplet extends Applet

By deriving your own applet class from Java's Applet class, you take advantage of inheritance and automatically gain all the basic functionality of an applet. You need only add your own custom code in order to make the applet perform as you like.
 

Next in the program, you can see the applet's data members being declared, as shown in listing 15.10.

Listing 15.10 LST15_10.TXT: DrawApplet's data members.

Point startPoint;
Point points[];
int numPoints;
boolean drawing;

The Point class, which is defined as part of the awt package, represents a data structure that can hold the X,Y coordinates of a single point on the screen. The integer numPoints contains the number of points in the Point array, points[], whereas the boolean value, drawing, tells the program whether the user is currently in drawing mode.

Exploring the init() Method

The init() member function is a method that's defined in the Applet class, but is overridden in DrawApplet to provide additional initialization for the applet. As you learn Chapter 17, "Advanced Applet Code," init() represents the first part of an applet's life cycle. In the case of DrawApplet, init() first initializes a new Point object to hold the starting point of the drawing:

startPoint = new Point(0, 0);

The new operator creates a new object, just as it does in C++. In this case, the new point has the value 0 stored in its x and y data members.

After creating the starting-point object, the program creates a new array of Point objects:

points = new Point[1000];

This array holds the coordinates of all the line segments that comprise the user's drawing. Here, the new operator is used again. However, this time the line has the number 1000 in square brackets, which tells Java to create a Point array containing 1,000 points.

In the next two lines, the init() method initializes the two remaining data members:

numPoints = 0;
drawing = false;

Finally, in the last line of the method, the program sets the size of the applet:

resize(400, 300);

The two arguments accepted by the resize() method are the new width and height of the applet.

Exploring the mouseDown() Method

Applets, like any other windowed application, must respond to messages sent by the system. Often these messages are generated when the user triggers an event in the application. For example, when the user clicks the left mouse button, a mouse-button event gets passed to the applet, which is handled in the mouseDown() function. The mouseDown() function's parameters are an Event object (which you learn more about in Chapter 20, "Exceptions and Events in Depth"), and the X and Y coordinates of the mouse click. Here's the method's signature:

public boolean mouseDown(Event evt, int x, int y)

In DrawApplet's version of mouseDown(), the program first checks to see whether the user is currently in drawing mode:

if (!drawing)

If he isn't, the mouse-button click indicates that the user wants to start drawing. In this case, the program sets the drawing flag to true and initializes the drawing's starting point to the mouse pointer's coordinates at the time of the click:

drawing = true;
startPoint.x = x;
startPoint.y = y;

If the program is already in drawing mode (drawing equals true), mouseDown()'s else clause simply sets the drawing flag to false:

else
drawing = false;

As you see when you examine the paint() method, setting drawing to false stops all drawing operations.

Exploring the mouseMove() Method

Whenever the user moves the mouse over the applet's display area, the applet receives a stream of mouse-movement messages. Your applet can respond to these messages by overriding the mouseMove() method (which is defined in the awt package's Component class). The mouseMove() method's signature is very similar to mouseDown()'s, receiving exactly the same parameters:

public boolean mouseMove(Event evt, int x, int y)

If the user is currently in drawing mode, he expects the program to draw a line when he moves the mouse. So, mouseMove() first checks the drawing flag to see whether the user is currently in drawing mode. The program also checks that the number of drawing points generated by the user is still less than 1,000:

if ((drawing) && (numPoints < 1000))

If the user is drawing (and if there's still room in the points[] array for more points), the function adds the new point to the points[] array:

points[numPoints] = new Point(x, y);
++numPoints;

The program then calls the repaint() method:

repaint();

The repaint() method forces the applet to redraw its display area, which, as you see in the next section, displays the user's drawing on the screen.

Exploring the paint() Method

An applet's paint() method is responsible for keeping the applet's display up to date. Usually, the code that draws to the applet's display area (or canvas, as the display area is sometimes called) is fully contained in the paint() method, which gets called whenever the applet needs to have its display redrawn. This might be when the applet first appears on the screen, when the applet has been revealed from under another window, or when the program implicitly calls repaint() by calling the repaint() method, which you saw in the previous section.

The paint() method's signature looks like this:

public void paint(Graphics g)

As you can see, the paint() method receives a Graphics object as a parameter. The Graphics object represents the graphical tasks, such as drawing shapes or setting fonts, that a Java program can handle. In DrawApplet, the program uses the Graphics object to draw lines on the screen.
 

Inside DrawApplet's version of paint(), the applet first saves the starting point for the line:

int oldX = startPoint.x;
int oldY = startPoint.y;

Then, the method start a for loop that iterates through the points[] array, using numPoints (the number of points stored in the array) as the loop-control variable:

for (int x=0; x<numPoints; ++x)

Inside the loop, the program draws a line from oldX and oldY to the next indexed point in the array:

g.drawLine(oldX, oldY, points[x].x, points[x].y);

The drawLine() function is a method of the Graphics class, so drawLine() can be accessed through g, which is the Graphics object passed into the paint() method as a parameter. The drawLine() method's four arguments are the X,Y coordinates of the line's starting point and the X,Y coordinates of the line's ending point.

After drawing the line, the program saves the end point of the current line to be used in the next iteration of the loop, as the starting point for the next line:

oldX = points[x].x;
oldY = points[x].y;

The loop continues until the entire drawing is reproduced in the applet's display area.

An Applet That Uses Controls

As you saw in the previous applet example, applets are interactive applications that can handle messages generated by both the system and the user. Another way, besides the mouse, that you can enable user interaction is by including controls—such as buttons, menus, list boxes, and text boxes—in your applet's display. Although controls are covered thoroughly in Chapter 31, "java.awt," you get an introduction to them now, as you create an applet that can connect you to various Web sites on the Internet.

Listing 15.11 is the Java source code for the applet in question, whereas listing 15.12 is the applet's HTML document. Before running this applet (by loading its HTML document into a Java-compatible browser, make your Internet connection. Then, when you run the applet, you see a window something like figure 15.5, which shows InternetApplet running in Netscape Navigator 2.0. Just click one of the connection buttons, and you automatically log onto the Web site associated with the button. Figure 15.6 shows where you end up when you click the CNet button.


FIG. 15.5

The InternetApplet applet uses buttons to provide an instant connection to eight different Web sites.


FIG. 15.6

The CNet button, for example, connects to CNet's terrific site.

Listing 15.11 InternetApplet.java: The InternetApplet applet.

import java.awt.*;
import java.applet.*;
import java.net.*;
public class InternetApplet extends Applet
{
boolean badURL;
public void init()
{
GridLayout layout = new GridLayout(2, 4, 10, 10);
setLayout(layout);
Font font = new Font("TimesRoman", Font.PLAIN, 24);
setFont(font);
Button button = new Button("Sun");
add(button);
button = new Button("Netscape");
add(button);
button = new Button("Microsoft");
add(button);
button = new Button("Macmillan");
add(button);
button = new Button("Time");
add(button);
button = new Button("CNet");
add(button);
button = new Button("Borland");
add(button);
button = new Button("Yahoo");
add(button);
badURL = false;
}
public void paint(Graphics g)
{
if (badURL)
g.drawString("Bad URL!", 60, 130);
}
public boolean action(Event evt, Object arg)
{
String str;
if (arg == "Sun")
str = "http://www.sun.com";
else if (arg == "Netscape")
str = "http://www.netscape.com";
else if (arg == "Microsoft")
str = "http://www.microsoft.com";
else if (arg == "Macmillan")
str = "http://www.mcp.com";
else if (arg == "Time")
str = "http://www.pathfinder.com";
else if (arg == "CNet")
str = "http://www.cnet.com";
else if (arg == "Borland")
str = "http://www.borland.com";
else
str = "http://www.yahoo.com";
try
{
URL url = new URL(str);
AppletContext context = getAppletContext();
context.showDocument(url);
}
catch (MalformedURLException e)
{
badURL = true;
repaint();
}

return true;
}
}

Listing 15.12 INTERNETAPPLET.HTML: InternetApplet's HTML document.

<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet
code="InternetApplet.class"
width=500
height=150
name="InternetApplet">
</applet>

Understanding the InternetApplet Applet

Now, take a look at the applet's source code. The first three lines enable the program to access the classes stored in Java's awt, applet, and net packages:

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

You're already familiar with the awt and applet packages. The net package contains the classes needed to log onto the Internet.

The applet's main class, which is derived from Applet, begins in the next line:

public class InternetApplet extends Applet

InternetApplet then declares its single data member:

boolean badURL;

The badURL data member is used in the program to notify the applet that the currently selected URL is no good.

Exploring the init() Method

Next comes the familiar init() method, where the applet can perform whatever initialization it requires. In this case, the applet first declares and sets a layout manager:

GridLayout layout = new GridLayout(2, 4, 10, 10);
setLayout(layout);

Java programs use layout managers to control where components in the program will appear on the screen. Java offers many types of layout managers, each represented by its own class in the awt package. (Refer to Chapter 30, "java.awt," for more information on layout managers.) If you don't create and set your own layout manager, Java uses the FlowLayout manager—which places components horizontally one after the other—by default. In InternetApplet, you're using a GridLayout manager, which organizes components into a grid. GridLayout's constructor takes four arguments:

These latter two arguments have default values of 0 if you want to leave them off.

The setLayout() function is a member of the Container class, which is a superclass (a parent class in the class hierarchy) of the Applet class. Its single argument is a reference to a layout-manager object. After calling setLayout(), Java knows to use the new layout manager rather than the default one.

After setting the applet's layout manager, the program creates and sets the font that'll be used for all text in the applet:

Font font = new Font("TimesRoman", Font.PLAIN, 24);
setFont(font);

The constructor for the Font class takes three arguments— the font's name, attribute, and size. The font's name can be Dialog, Helvetica, TimesRoman, Courier, or Symbol, whereas the attribute can be Font.PLAIN, Font.ITALIC, or Font.BOLD. The setFont() method sets the new font for the applet.

The next task is to create, and add to the applet, the button controls used to select Web sites. Listing 15.13 shows the code that accomplishes this task.

Listing 15.13 LST15_13.TXT: Creating button controls.

Button button = new Button("Sun");
add(button);
button = new Button("Netscape");
add(button);
button = new Button("Microsoft");
add(button);
button = new Button("Macmillan");
add(button);
button = new Button("Time");
add(button);
button = new Button("CNet");
add(button);
button = new Button("Borland");
add(button);
button = new Button("Yahoo");
add(button);

The Button class's constructor takes a single argument, which is the text label that appears in the button when it's displayed. The add() method adds the button to the next available cell in the GridLayout manager.

Finally, init() sets the badURL flag to false:

badURL = false;

Exploring the action() Method

Most user events caused in an applet can be handled by your overriding the action() method. The signature for the action() method looks like this:

public boolean action(Event evt, Object arg)

As you can see, action() receives two parameters—an Event object and an Object object. You learn more about these objects in Chapter 20, "Exceptions and Events in Depth." For now, it's enough to know that, in the case of a button control, arg is the button's text label.

When the user clicks one of the applet's buttons, the action() method is called. As I said, the arg parameter is the text label of the button that was clicked, so it's pretty easy to determine which button the user selected. To do this, InternetApplet uses an if-else statement to check the button's label. When the program finds the button the user selected, it sets str, which is an object of Java's String class, to the selected URL, as shown in listing 15.14.

Listing 15.14 LST15_14.TXT: Getting the requested URL.

String str;
if (arg == "Sun")
str = "http://www.sun.com";
else if (arg == "Netscape")
str = "http://www.netscape.com";
else if (arg == "Microsoft")
str = "http://www.microsoft.com";
else if (arg == "Macmillan")
str = "http://www.mcp.com";
else if (arg == "Time")
str = "http://www.pathfinder.com";
else if (arg == "CNet")
str = "http://www.cnet.com";
else if (arg == "Borland")
str = "http://www.borland.com";
else
str = "http://www.yahoo.com";

After obtaining the selected URL, the applet can connect to the Web site. Before doing this, though, the program must set up a try and catch program block, because the URL class's constructor throws a MalformedURLException exception, which must be caught by your program. (You learn more about exceptions in Chapter 20, "Exceptions and Events in Depth.") The try program block attempts to create the URL object and connect to the Web site, as shown in listing 15.15.

Listing 15.15 LST15_15.TXT: Connecting to a Web site.

try
{
URL url = new URL(str);
AppletContext context = getAppletContext();
context.showDocument(url);
}

In the try block, the program first tries to create a URL object from the URL text string. If the construction fails, the URL class throws a MalformedURLException exception, and program execution continues at the catch program block, which you look at soon. If the URL object gets constructed successfully, the program calls the getAppletContext() method to get a reference to the applet's AppletContext object. This object's showDocument() method is what connects the applet to the chosen URL.

If the URL class's constructor throws an exception, program execution jumps to the catch program block, which is shown in listing 15.15.

Listing 15.15 LST15_15.TXT: The catch program block.

catch (MalformedURLException e)
{
badURL = true;
repaint();
}

In the catch program block, the program simply sets the badURL flag to true and calls repaint() to display an error message to the user.

Exploring the paint() Method

Listing 15.17 shows the applet's paint() method, which does nothing more than display an error message if the badURL flag is set to true.

Because the URLs are hard-coded into the program, it's not likely that the URL will construct improperly. If you were to change a button's URL, though, the error message lets you know if you typed the URL incorrectly.
 

Listing 15.15 LST15_17.TXT: The paint() method.

public void paint(Graphics g)
{
if (badURL)
g.drawString("Bad URL!", 60, 130);
}

The drawString() function, which is a method of the Graphics class, displays a text string on the screen. Its three arguments are the string to display, and the X,Y coordinates at which to display the string.

Conclusion

As you've learned, creating an applet can be a relatively easy process. The classes that come packaged with Java give you the power to do everything from capture mouse events to connect to Web sites. However, this chapter just scratched the surface of what you can do with applets. In the following chapter, you'll learn more sophisticated techniques for creating custom applets.


Previous PageTOCNext Page

| Previous Chapter | Next Chapter |

| Table of Contents | Book Home Page |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.