Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

BarChart

Draws a simple bar chart.

Blink

Displays blinking text in different colors.

CardTest

Demonstrates several GUI components and layouts.

Clock

Draws a clock with rotating hands, the current date and the current

 

time. The clock updates once per second.

DitherTest

Demonstrates drawing with a graphics technique known as dithering

 

that allows gradual transformation from one color to another.

DrawTest

Allows the user mouse to draw lines and points in different colors by

 

dragging the mouse.

Fractal

Draws a fractal. Fractals typically require complex calculations to

 

determine how they are displayed.

GraphicsTest

Draws shapes to illustrate graphics capabilities.

GraphLayout

Draws a graph consisting of many nodes (represented as rectangles)

 

connected by lines. Drag a node to see the other nodes in the graph

 

adjust on the screen and demonstrate complex graphical interactions.

ImageMap

Demonstrates an image with hot spots. Positioning the mouse pointer

 

over certain areas of the image highlights the area and displays a

 

message in the lower-left corner of the applet container window.

 

Position over the mouth in the image to hear the applet say "hi."

JumpingBox

Moves a rectangle randomly around the screen. Try to catch it by

 

clicking it with the mouse!

MoleculeViewer

Presents a three-dimensional view of several chemical molecules.

 

Drag the mouse to view the molecule from different angles.

NervousText

Draws text that jumps around the applet.

SimpleGraph

Draws a complex curve.

SortDemo

Compares three sorting techniques. Sorting (described in Chapter 16)

 

arranges information in orderlike alphabetizing words. When you

 

execute this example from a command window, three appletviewer

 

windows appear. When you execute this example in a browser, the

 

three demos appear side-by-side. Click in each demo to start the

 

sort. Note that the sorts all operate at different speeds.

SpreadSheet

Demonstrates a simple spreadsheet of rows and columns.

TicTacToe

Allows the user to play Tic-Tac-Toe against the computer.

WireFrame

Draws a three-dimensional shape as a wire frame. Drag the mouse

 

to view the shape from different angles.

 

 

[Page 961]

Change directories to subdirectory TicTacToe, where you will find the HTML document example1.html that is used to execute the applet. In the command window, type the command

appletviewer example1.html

and press Enter. This executes the appletviewer applet container, which loads the HTML document example1.html specified as its command-line argument. The appletviewer determines from the document which applet to load and executes the applet. Figure 20.2 shows several screen captures of playing Tic-Tac-Toe with this applet.

Figure 20.2. TicTacToe applet sample execution.

(This item is displayed on page 962 in the print version)

[View full size image]

You are player X. To interact with the applet, point the mouse at the square where you want to place an X and click the mouse button. The applet plays a sound and places an X in the square if the square is open. If the square is occupied, this is an invalid move and the applet plays a different sound indicating that you cannot make the specified move. After you make a valid move, the applet responds by making its own move.

To play again, click the appletviewer's Applet menu and select the Reload menu item (Fig. 20.3). To terminate the appletviewer, click the appletviewer's Applet menu and select the Quit menu item.

[Page 962]

Figure 20.3. Applet menu in the appletviewer.

[View full size image]

DrawTest Applet

The DrawTest applet allows you to draw lines and points in different colors. In the command window, change directories to directory applets, then to subdirectory DrawTest. You can move up the directory tree incrementally toward demo by issuing the command "cd .." in the command window. The DrawTest directory contains the example1.html document that is used to execute the applet. In the command window, type the command

appletviewer example1.html

and press Enter. The appletviewer loads example1.html, determines from the document which applet to load and executes the applet. Figure 20.4 shows a screen capture after some lines and points have been drawn.

Figure 20.4. DrawTest applet sample execution.

(This item is displayed on page 963 in the print version)

[View full size image]

By default the applet allows you to draw black lines by dragging the mouse across the applet. When you drag the mouse, note that the start point of the line always remains in the same place and the end point of the line follows the mouse pointer around the applet. The line is not permanent until you release the mouse button.

[Page 963]

Select a color by clicking one of the radio buttons at the bottom of the applet. You can select from red, green, blue, pink, orange and black. Change the shape to draw from Lines to Points by selecting Points from the combo box. To start a new drawing, select Reload from the appletviewer's Applet menu.

Java2D Applet

The Java2D applet demonstrates many features of the Java 2D API (which we introduced in Chapter 12). Change directories to the jfc directory in the JDK's demo directory, then change to the Java2D directory. In the command window, type the command

appletviewer Java2Demo.html

and press Enter. The appletviewer loads Java2Demo.html, determines from the document which applet to load and executes the applet. Figure 20.5 shows a screen capture of one of this applet's many demonstrations of Java's two-dimensional graphics capabilities.

Figure 20.5. Java2D applet sample execution.

(This item is displayed on page 964 in the print version)

[View full size image]

At the top of the applet are tabs that look like file folders in a filing cabinet. This demo provides 12 tabs with Java 2D API features demonstrated on each tab. To change to a different part of the demo, simply click a different tab. Also, try changing the options in the upper-right corner of the applet. Some of these affect the speed with which the applet draws the graphics. For example, click the checkbox to the

left of the word Anti-Aliasing to turn off anti-aliasing (a graphics technique for producing smoother onscreen graphics in which the edges of the graphic are blurred). When this feature is turned off, the animation speed increases for the animated shapes at the bottom of the demo (Fig. 20.5). This performance increase occurs because shapes that are not anti-aliased are less complex to draw.

[Page 964]

20.3. Simple Java Applet: Drawing a String

Every Java applet is a graphical user interface on which you can place GUI components using the techniques introduced in Chapter 11 or draw using the techniques demonstrated in Chapter 12. In this chapter, we will demonstrate drawing on an applet. Examples in Chapters 21, 23 and 24 demonstrate building an applet's graphical user interface.

Now let's build an applet of our own. We begin with a simple applet (Fig. 20.6) that draws "Welcome to Java Programming!" on the applet. Figure 20.7 shows this applet executing in two applet containersthe appletviewer and the Microsoft Internet Explorer Web browser. At the end of this section, you will learn how to execute the applet in a Web browser.

Figure 20.6. Applet that draws a string.

(This item is displayed on page 965 in the print version)

1

//

Fig. 20

.6: WelcomeApplet.java

 

 

 

2

//

A first

applet in Java.

 

 

 

 

 

3

import

java.awt.Graphics;

//

program

uses

class

Graphics

4

import

javax.swing.JApplet;

//

program

uses

class

JApplet

5

 

 

 

 

 

 

 

 

 

6public class WelcomeApplet extends JApplet

7{

8 // draw text on applet's background

9public void paint( Graphics g )

10{

11// call superclass version of method paint

12super.paint( g );

13

14// draw a String at x-coordinate 25 and y-coordinate 25

15g.drawString( "Welcome to Java Programming!", 25, 25 );

16} // end method paint

17} // end class WelcomeApplet

Figure 20.7. Sample outputs of the WelcomeApplet in Fig. 20.6.

(This item is displayed on page 965 in the print version)

[View full size image]

Creating the Applet Class

Line 3 imports class Graphics to enable the applet to draw graphics, such as lines, rectangles, ovals and strings of characters. Class JApplet (imported at line 4) from package javax.swing is used to create applets. As with applications, every Java applet contains at least one public class declaration. An applet container can create only objects of classes that are public and extend JApplet (or the Applet class from early versions of Java). For this reason, class WelcomeApplet (lines 617) extends JApplet.

[Page 965]

[Page 966]

An applet container expects every Java applet to have methods named init, start, paint, stop and destroy, each of which is declared in class JApplet. Each new applet class you create inherits default implementations of these methods from class JApplet. These methods can be overridden (redefined) to perform tasks that are specific to your applet. Section 20.4 discusses each of these methods in more detail.

When an applet container loads class WelcomeApplet, the container creates an object of type WelcomeApplet, then calls three of the applet's methods. In sequence, these three methods are init, start and paint. If you do not declare these methods in your applet, the applet container calls the inherited versions. The superclass methods init and start have empty bodies, so they do not perform any tasks. The superclass method paint does not draw anything on the applet.

You might wonder why it is necessary to inherit methods init, start and paint if their default implementations do not perform tasks. Some applets do not use all three of these methods. However, the applet container does not know that. Thus, it expects every applet to have these methods, so that it can provide a consistent start-up sequence for each applet. This is similar to applications' always starting execution with main. Inheriting the "default" versions of these methods guarantees that the applet container can execute each applet uniformly. Also, inheriting default implementations of these methods allows the programmer to concentrate on defining only the methods required for a particular applet.

Overriding Method paint for Drawing

To enable our applet to draw, class WelcomeApplet overrides method paint (lines 916) by placing statements in the body of paint that draw a message on the screen. Method paint receives a parameter of type Graphics (called g by convention), which is used to draw graphics on the applet. You do not call method paint explicitly in an applet. Rather, the applet container calls paint to tell the applet when to draw, and the applet container is responsible for passing a Graphics object as an argument.

Line 12 calls the superclass version of method paint that was inherited from JApplet. This statement should be the first statement in every applet's paint method. Omitting it can cause subtle drawing errors in applets that combine drawing and GUI components.

Line 15 uses Graphics method drawString to draw Welcome to Java Programming! on the applet. The method receives as arguments the String to draw and the x-y coordinates at which the bottom-left corner of the String should appear in the drawing area. When line 15 executes, it draws the String on the applet at the coordinates 25 and 25.

20.3.1. Executing an Applet in the appletviewer

As with application classes, you must compile an applet class before it can execute. After creating class WelcomeApplet and saving it in the file WelcomeApplet.java, open a command window, change to the directory in which you saved the applet class declaration and compile class WelcomeApplet.

Recall that applets are embedded in Web pages for execution in an applet container (appletviewer or a browser). Before you can execute the applet, you must create an HTML (HyperText Markup Language) document that specifies which applet to execute in the applet container. Typically, an HTML document ends with an ".html" or ".htm" file-name extension. Figure 20.8 shows a simple HTML documentWelcomeApplet.htmlthat loads the applet defined in Fig. 20.6 into an applet container. [Note: If you are interested in learning more about HTML, the CD that accompanies this book contains three chapters from our book Internet and World Wide Web How to Program, Third Edition that introduce the current version of HTML (known as XHTML) and the Web page formatting capability known as Cascading Style Sheets (CSS).]

[Page 967]

Figure 20.8. WelcomeApplet.html loads WelcomeApplet (Fig. 20.6) into an applet container.

1

<html>

2

<applet code = "WelcomeApplet.class" width = "300" height = "45">

3</applet>

4</html>

Most HTML elements are delimited by pairs of tags. For example, lines 1 and 4 of Fig. 20.8 indicate the beginning and the end, respectively, of the HTML document. All HTML tags begin with a left angle bracket, <, and end with a right angle bracket, >. Lines 23 specify an applet element that tells the applet container to load a specific applet and defines the size of the applet's display area (its width and height in pixels) in the applet container. Normally, the applet and its corresponding HTML document are stored in the same directory on disk. Typically, a browser loads an HTML document from a computer (other than your own) connected to the Internet. However, HTML documents also can reside on your computer (as you saw in Section 20.2). When an applet container encounters an HTML document that contains an applet, the applet container automatically loads the applet's .class file (or files) from the same directory on the computer in which the HTML document resides.

The applet element has several attributes. The first attribute in line 2, code = "WelcomeApplet.class", indicates that the file WelcomeApplet.class contains the compiled applet class. The second and third attributes in line 2 indicate the width (300) and the height (45) of the applet in pixels. The </applet> tag (line 3) terminates the applet element that began at line 2. The </html>

tag (line 4) terminates the HTML document.

Look-and-Feel Observation 20.1

To ensure that it can be viewed properly on most computer screens, an applet should generally be less than 1024 pixels wide and 768 pixels talldimensions supported by most computer screens.

Common Programming Error 20.1

Forgetting the ending </applet> tag prevents the applet from executing in some applet containers. The appletviewer terminates without indicating an error. Some Web browsers simply ignore the incomplete applet element.

Error-Prevention Tip 20.1

If you receive a MissingResourceException error message when loading an applet into the appletviewer or a browser, check the <applet> tag in the HTML document carefully for syntax errors, such as commas (,) between the attributes.

The appletviewer understands only the <applet> and </applet> HTML tags and ignores all other tags in the document. The appletviewer is an ideal place to test an applet and ensure that it executes properly. Once the applet's execution is verified, you can add its HTML tags to a Web page that others can view in their Web browsers.

[Page 968]

To execute WelcomeApplet in the appletviewer, open a command window, change to the directory containing your applet and HTML document, then type

appletviewer WelcomeApplet.html

Error-Prevention Tip 20.2

Test your applets in the appletviewer applet container before executing them in a Web browser. Browsers often save a copy of an applet in memory until all the browser's windows are closed. If you change an applet, recompile it, then reload it in your browser, the browser may still execute the original version of the applet. Close all your browser windows to remove the old applet from memory. Open a new browser window and load the applet to see your changes.

Error-Prevention Tip 20.3

Test your applets in every Web browser in which they will execute to ensure that they operate correctly.

20.3.2. Executing an Applet in a Web Browser

The sample program executions in Fig. 20.6 demonstrate WelcomeApplet executing in the appletviewer and in Microsoft Internet Explorer Web browser. To execute an applet in Internet Explorer, perform the following steps:

1.Select Open... from the File menu.

2.In the dialog box that appears, click the Browse... button.

3.In the dialog box that appears, locate the directory containing the HTML document for the applet you wish to execute.

4.Select the HTML document.

5.Click the Open button.

6.Click the OK button.

[Note: The steps for executing applets in other Web browsers are similar.]

If your applet executes in the appletviewer, but does not execute in your Web browser, Java may not be installed and configured for your browser. In this case, visit the Web site java.com and click the Get It Now button to install Java for your browser. In Internet Explorer, if this does not fix the problem, you might need to manually configure Internet Explorer to use J2SE 5.0. To do so, click the Tools menu and select Internet Options..., then click the Advanced tab in the window that appears. Locate the option "Use JRE v1.5.0 for <applet> (requires restart)" and ensure that it is checked, then click OK. Close all your browser windows before attempting to execute another applet in the browser.