<<

962 Chapter 23 Applets and Web Start

Summary Section 23.1 Introduction • Applets (p. 942) are Java programs that are typically embedded in HTML (Extensible Hyper- Text Markup Language) documents—also called web pages. When a Java-enabled loads a web page containing an applet, the applet downloads into the browser and executes. • The application in which an applet executes is known as the applet container (p. 942). It’s the applet container’s responsibility to load the applet’s class(es), create an instance of the applet and manage its life cycle. The JDK includes an applet container called the appletviewer (p. 942) for testing applets as you develop them and before you embed them in web pages. • Web browsers execute Java applets via the Java Plug-In (p. 942).

Section 23.2 Sample Applets Provided with the JDK • To re-execute an applet in the appletviewer,clicktheappletviewer’s Applet menu and select the Reload menu item. • To terminate the appletviewer,selectQuit from the appletviewer’s Applet menu.

Section 23.3 Simple : Drawing a String • Every Java applet is a graphical user interface on which you can place GUI components or draw. • Class JApplet (p. 948) from package javax.swing is used to create applets. • An applet container can create only objects of classes that are public and extend JApplet (or the Applet class from early versions of Java). • An applet container expects every Java applet to have methods named init, start, paint, stop and destroy (p. 949), each of which is declared in class JApplet. Each new applet class you create inherits default implementations of these methods from class JApplet. • When an applet container loads an applet, it creates an object of the applet’s type, then calls the applet’s init, start and paint methods. • To enable an applet to draw, override its paint method (p. 949). The applet container calls paint to tell the applet when to draw. • The first statement in method paint should be a call to the superclass method paint. • Before you can execute an applet, you must create an HTML (Extensible HyperText Markup Language) document that specifies which applet to execute in the applet container. Typically, an HTML document ends with an “.”or“.htm” file-name extension. •Anapplet element tells the applet container to load a specific applet and defines the size of its display area (its width and height in pixels) in the applet container. • Normally, an applet and its corresponding HTML document are stored in the same directory. • When an applet container encounters an HTML document that contains an applet, the container automatically loads the applet’s .class file(s) from the same location as the HTML document. •Theappletviewer understands only the and HTML tags (p. 950) and ig- nores all other tags in the document. Section 23.4 Applet Life-Cycle Methods •Methodinit (p. 949) is called once by the applet container to initialize an applet when it’s loaded. • Method start (p. 949) is called by the applet container after method init completes execution. In addition, if the user browses to another and later returns to the applet’s HTML page, method start is called again. • Method paint is called by the applet container after methods init and start. Summary 963

• Method stop (p. 949) is called by the applet container when the user leaves the applet’s web page by browsing to another web page. • Method destroy (p. 949) is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows and may also occur at the browser’s discretion when the user has browsed to other web pages.

Section 23.5 Initialization with Method init • Graphics method drawString draws a String at a specified location. • Graphics method drawRect draws a rectangle at the specified upper-left corner, width and height. Section 23.6 Sandbox Security Model • A browser downloads an applet without the user’s knowledge—it’s just another element of the web page the user happens to be visiting. • To combat malicious code, the Java platform uses a sandbox security model (p. 955) that pro- vides a mechanism for executing downloaded code safely. Downloaded code cannot access local system resources, and an applet can interact only with the server from which it was downloaded. • You can “digitally sign” an applet that requires access to local system resources. If the user indi- cates that he/she trusts the applet’s source, only then will the applet be able to access the local computer’s resources. Section 23.7 Java Web Start and the Java Network Launch Protocol (JNLP) • Java Web Start (p. 956) is a framework for running downloaded programs outside the browser. • Users can launch robust applets and applications by clicking a hyperlink in a web page, and can quickly and easily install the programs on their computers. • Java Web Start can be configured to ask the user if a desktop icon should be created so the user can launch the program directly from the desktop. Downloaded programs can also have an “off- line mode” for execution when the computer is not connected to the Internet. • When you execute a program via Java Web Start, the program is downloaded and cached (stored) on the user’s computer. The next time the user executes that program, Java Web Start launches it from the cache. • If the program has been updated since it was last lauched, Java Web Start can automatically download the new version, so a user always has the most up-to-date version. • A Java Network Launch Protocol (JNLP; p. 956) document provides the information that Java Web Start needs to download and run a program. • Programs launched via Java Web Start execute using the sandbox security model. The user can permit access to the local file system, the clipboard and other services via the JNLP APIs.

Section 23.7.1 Packaging the DrawTest Applet for Use with Java Web Start •Thejar command (p. 957) is used to create JAR files. Option c indicates that the command should create a new JAR file (p. 957). Option v indicates that the command should produce ver- bose output (p. 957). Option f indicates that the next argument in the command line is the new JAR file’s name (p. 957).

Section 23.7.2 JNLP Document for the DrawTest Applet • A JNLP document describes the contents of the JAR file and specifies which file in the JAR is the so-called main-class (p. 957) that begins the program’s execution. • JNLP documents are written in Extensible Markup Language (XML)—a widely supported stan- dard for describing data (p. 957). 964 Chapter 23 Applets and Java Web Start

• JNLP is a so-called XML vocabulary that describes the information Java Web Start needs to launch a program. •Thejnlp element’s (p. 958) codebase attribute specifies the pathwheretheJNLPdocumentand the JAR file are stored. The href attribute specifies the JNLP file that launches the program. • Typically, the codebase references a directory on a web server with an http:// URL. •Theinformation element (p. 959) provides details about the program. •Thetitle element (p. 959) specifies a title for the program. •Thevendor element (p. 959) specifies who created the program. •Thedesktop element nested in the shortcut element (p. 959) tells Java Web Start to ask users whether they wish to install a desktop shortcut. •Theoffline-allowed (p. 959) element indicates that a program can be launched via Java Web Start even when the computer is not connected to the Internet. •Theresources element (p. 959) contains a java element (p. 959) that lists the minimum version of Java required to execute the program and a jar element (p. 959) that specifies the location of the JAR file. •Theapplet-desc (p. 959) element’s name attribute specifies the applet’s name. The main-class attribute specifies the main applet class. The width and height (p. 950) attributes specify the width and height in pixels, respectively, of the window in which the applet will execute. • To launch the applet via Java Web Start you can use the javaws command (p. 959). You can also use your operating system’s file manager to locate the JNLP on your computer and double click its file name. Normally, a JNLP file is referenced from a web page via a hyperlink. • WhenyourunanappletviaJavaWebStartthefirsttimeandtheJNLPdocumentspecifiesthat a desktop icon should be installed, you’ll be presented with a dialog that enables you to decide whether to install the desktop icon. If you click OK, a new icon labeled with the title specified in the JNLP document appears on the desktop. • You can view the installed Java Web Start programs in the Java Cache Viewer by typing the com- mand javaws -viewer in a command window. •TheJava Cache Viewer enables you to manage the installed Java Web Start programs. You can run a selected program, create a desktop shortcut, delete installed programs, and more.

Self-Review Exercise 23.1 Fill in the blanks in each of the following: a) Java applets begin execution with a series of three method calls: , and . b) The method is invoked for an applet each time a browser’s user leaves an HTML page on which the applet resides. c) Every applet should extend class . d) The or a browser can be used to execute a Java applet. e) The method is called each time the user of a browser revisits the HTML page on which an applet resides. f) To load an applet into a browser, you must first define a(n) file. g) Method is called once when an applet begins execution. h) Method is invoked to draw on an applet. i) Method is invoked for an applet when the browser removes it from memory. j) The and HTML tags specify that an applet should be loaded into an applet container and executed. Answers to Self-Review Exercise 965

k) is a framework for running downloaded programs outside the browser. l) A(n) document provides the information that Java Web Start needs to down- load and run a program. m) The enables you to manage the Java Web Start programs on your system.

Answers to Self-Review Exercise 23.1 a) init, start, paint.b)stop.c)JApplet (or Applet). d) appletviewer.e)start.f) HTML. g) init.h)paint.i)destroy.j), . k) Java Web Start. l) Java Network Launch Protocol (JNLP). m) Java Cache Viewer.

Exercises 23.2 (Arithmetic) Write an applet that asks the user to enter two floating-point numbers, obtains the two numbers from the user and draws their sum, product (multiplication), difference and quo- tient (division). Use the techniques shown in Fig. 23.9. 23.3 (Comparing Numbers) Write an applet that asks the user to enter two floating-point num- bers, obtains the numbers from the user and displays the two numbers, then displays the larger num- ber followed by the words "is larger" as a string on the applet. If the numbers are equal, the applet should print the message "These numbers are equal." Use the techniques shown in Fig. 23.9. 23.4 (Arithmetic and Numeric Comparisons) Write an applet that inputs three floating-point numbers from the user and displays the sum, average, product, smallest and largest of these numbers as strings on the applet. Use the techniques shown in Fig. 23.9. 23.5 (Diameter, Circumference and Area of a Circle) Write an applet that asks the user to input the radius of a circle as a floating-point number and draws the circle’s diameter, circumference and area. Use the value 3.14159 for π. Use the techniques shown in Fig. 23.9. [Note: You may also use the predefined constant Math.PI for the value of π. This constant is more precise than the value 3.14159. Class Math is defined in the java.lang package, so you do not need to import it.] Use the following formulas (r is the radius): diameter =2r circumference =2πr area = πr2

23.6 (Largest and Smallest) Write an applet that reads five integers, determines which are the largest and smallest integers in the group and prints them. Draw the results on the applet. 23.7 (Draw a Checkerboard Pattern) Write an applet that draws a checkerboard pattern as follows:

******** ******** ******** ******** ******** ******** ******** ********

23.8 (Drawing Rectangles) Write an applet that draws rectangles of different sizes and locations. 23.9 (Drawing Rectangles Based on User Input) Write an applet that allows the user to input values for the arguments required by method drawRect, then draws a rectangle using the four input values. 966 Chapter 23 Applets and Java Web Start

23.10 (Drawing Ovals and Rectangles) Class Graphics contains method drawOval,whichtakesas arguments the same four arguments as method drawRect.TheargumentsformethoddrawOval specify the “bounding box” for the oval—the sides of the bounding box are the boundaries of the oval. Write a Java applet that draws an oval and a rectangle with the same four arguments. The oval will touch the rectangle at the center of each side. 23.11 (Drawing Ovals and Rectangles) Modify the solution to Exercise 23.10 to output ovals of different shapes and sizes. 23.12 (Drawing Ovals Based on User Input) Write an applet that allows the user to input the four arguments required by method drawOval, then draws an oval using the four input values. 23.13 (TicTacToe Demonstration Applet with Java Web Start) Package the TicTacToe demon- stration applet from the JDK (discussed in Section 23.2) for use with Java Web Start, then copy the JNLP document in Fig. 23.12 and modify it so that it launches the TicTacToe applet.