CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
Learning How Applets Work
Now that Java is making 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, the core of interest in the language remains in a new 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. Programming applets with Java is much different from creating applications with Java. Because applets must be downloaded off a page each time they are run, applets are 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:
Setting up an applet
Displaying information in an applet
Stopping and starting an applet
Putting an applet on a Web page
Using applet HTML tags and attributes
Standard Applet Methods
All applets are subclasses of the Applet subclass, which is part of the java.applet package of classes. Being part of this hierarchy enables the applets that you write to use all the behavior and attributes they need to be run off of a World Wide 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 other functions.
In applications, programs begin running with the first statement of the main( block statement and end with the last 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
Something happens that requires the applet window to be redisplayed
The program stops at a specific point
The program restarts after a stop
The program is unloaded as it finishes running
The following is an example of a bare-bones applet:
public class Skeleton extends java.applet.Applet
Note that unlike applications, applet class files must be public in order to work. (However, if your applet uses other class files of your own creation, they do not have to be declared public.) This class inherits all of 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. The two methods you will override most often are paint( and init().
The paint() Method
The paint( method should be a part of almost every applet that you write because you can't display anything without it. 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:
repaint(
Otherwise, the main reason paint( occurs is when something is changed in the browser or the operating system running the browser. For example, if a Windows 95 user minimizes a Web page containing an applet, the paint( method will be called to redisplay everything that was on-screen in the applet when the applet is later restored to full-size.
Unlike the other methods that you will be learning about during this hour, paint( takes an argument. The following is an example of a simple paint( method:
public class paint(Graphics screen)
The argument is a Graphics object. The Graphics class of objects is used to handle all attributes and behavior that are needed to display text, graphics, and other information on-screen. (You'll learn about drawString( , one of the methods of the Graphics class, later this hour.) If you are using a Graphics object in your applet, you have to add the following import statement before the class statement at the beginning of the source file:
import java.awt.Graphics;
If you are using several classes that are a part of the java.awt package of classes, use the statement import java.awt.*; instead. It makes all of these classes available for use in your program.
The init() Method
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.
Caution: Variables and objects should not be created inside an init( method because they 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 that you need to use throughout a class as object variables right after the class statement and before any methods.
The start() and stop() Methods
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.
In the programs that you'll write as you're starting out with the Java language, start( and stop() will have the most use in animation. You'll learn more about this use during Hour 18, 'Creating Animation.'
The destroy() Method
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 in rare instances when something has been changed during a program and should be restored to its original state. It's another method that 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 commands are used to describe the applet, and the Web browser loads it 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 < and > 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'>
You can place applets on a Web page 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 Applet class.
If there is no CODEBASE attribute, all files associated with the applet should be in the same directory as the Web page that loads the program. CODEBASE should contain a reference to the directory or subdirectory 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 subdirectory.
The HEIGHT and WIDTH attributes designate the exact size of the applet window on the Web page and 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. In the preceding example, a line of text is displayed indicating that Java is required to play the game.
Another attribute that you can use with applets is ALIGN. It designates how the applet will be displayed in relation to the surrounding material on the page, including text and graphics. Values include ALIGN='Left', ALIGN='Right', and others.
A Sample Applet
The first program that you wrote was a Java application that
revealed a depressing fact about the
Load your word processor and create a new file called BigDebtApplet.java. Enter the text of Listing 1 into the file and save it when you're done.
Listing 1. The full text of BigDebtApplet.java.
1: import java.awt.*;
2:
3: public class BigDebtApplet extends java.applet.Applet
public void paint(Graphics screen)
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.
Using the drawString() Method
The drawString( method is one of the things you can use in a paint() method to display information. It is similar in function to System.out.println( statement, which cannot be used in an applet. The drawString( method is part of the Graphics class, so you must use it in the paint() method or another method that has the Graphics object that was sent to the paint() method.
The following three arguments are sent to drawString( :
The text to display, which can be several different strings and variables strung together with the operator
The x position (in an (x,y) coordinate system) where the string should be displayed
The y position where the string should be displayed
The (x,y) coordinate system in an applet is used with several methods. It begins with the (0 ) point in the upper-left corner of the applet window. Figure 1 shows how the (x,y) coordinate system works in conjunction with the statement on Line 12 of BigDebtApplet.java.
Figure 1. <../art/13/13tja01.jpg> Drawing a string to an (x,y) position.
Testing the BigDebtApplet Program
Although you have compiled the BigDebtApplet program into a class file, you cannot run it using the java interpreter. If you do, you'll get an error message such as the following:
In class BigDebtApplet: void main(String argv[]) is not defined
The error occurs because the java interpreter runs Java applications beginning with the first statement of the main( block. To run an applet, you need to create a Web page that loads the applet. To create a Web page, open up a new file on your word processor and call it BigDebtApplet.html. Enter Listing 2 and then save the file.
Listing 2. The full text of BigDebtApplet.html.
1: <html>
2: <head>
3: <title>The Big Debt Applet</title>
4: </head>
5: <body bgcolor='#000000' text='#FF00FF'>
6: <center>
7: This a Java applet:<br>
8: <applet code='BigDebtApplet.class' height=150 width=300>
9: You need a Java-enabled browser to see this.
10: </applet>
11: </body>
12: </html>
Normally, you can test the Java applets that you write using the appletviewer
tool that comes with the Java Developer's Kit. You can see the output of the BigDebtApplet
applet by typing the following:
appletviewer BigDebtApplet.html
However, appletviewer only runs the applets that are included in a Web page and does not handle any of the other elements such as text and images. To see the BigDebtApplet.html file, load it into a browser that can handle Java programs, such as the current versions of Microsoft Internet Explorer and Netscape Navigator. Figure 2 shows a screen capture of BigDebtApplet.html loaded into Internet Explorer.
Figure 2. <../art/13/13tja02.jpg> The BigDebtApplet program on a Web page displayed by Microsoft Internet Explorer.
Caution: At the time of this writing, the current versions of Netscape Navigator and Microsoft Internet Explorer do not support any new feature introduced with version 1.1 of the Java language. This hour's applet works, but many others in later hours do not. Use the appletviewer tool to run applets unless you know your browser software fully supports Java 1.1.
Workshop: Enhancing the BigDebtApplet Project
As a short exercise to close out the hour, you'll enhance the BigDebtApplet program by making it accumulate the debt over time, displaying how much the national debt grows each second.
Open up a new file with your word processor and call it Ouch.java. Enter Listing 3 and save the file when you're done.
Listing 3. The full text of Ouch.java.
1: import java.awt.*;
2: import java.util.*;
3:
4: public class Ouch extends java.applet.Applet
This file uses an empty for loop in Line 11 to approximate the passage of a
second's time. Whether it actually pauses for a second depends on your
processor speed and anything else that's currently running on your computer.
The call to repaint(
in Line 13 at the end of the paint() method causes the paint() method to
be called again, starting over at the beginning of the method on Line 9.
To try out the program, you need to compile it with the javac compiler tool and create a Web page that runs the applet. Create a new file on your word processor and enter Listing 4 into the file. Save it when you're done.
Listing 4. The full text of Ouch.html.
1: <applet code='Ouch.class' height=300 width=300>
2: </applet>
This Web page only contains the HTML tags that are required to add an applet to
a page. Load this Web page into the appletviewer tool by typing the
following at a command line:
appletviewer Ouch.html
You will see an applet that begins with the calculation of a second's worth of debt. At a regular interval, another second's debt will be added. The following is an example of the text that is displayed as the applet runs:
13 second's worth of debt is $8879
Summary
This hour was the first of several that will focus on the development of applets. You got a chance to become acquainted with the init( and paint() methods, which you will be using frequently when you're developing applets.
Writing applets is a good way for beginners to develop their skills as Java programmers for the following reasons:
Applets are usually smaller in scope, making their creation a less daunting task.
You can find thousands of sample applets on the World Wide Web, including many with the source file available to learn from.
You can make applets available to a global audience at low to no cost through the Web, exposing your work to more people who can offer comments and suggestions.
There's a 'code war' of sorts afoot among the hundreds of Java programmers who are putting their work on the Web, and many new applets announced on sites like <https://www.jars.com> demonstrate new things that can be done with the language.
Q&A
Q Can
arguments be sent to applets, as they can to applications?
A You can't use arguments, but
parameters serve a similar function to arguments in applet programming. You can
use the <PARAM> tag with its NAME and VALUE attributes to send parameters to Java
programs. It's described fully in Hour 15, 'Sending Parameters to
Applets.'
Q Is there a reason why the CODEBASE
attribute should be used in an <APPLET> tag?
A If all Java programs are grouped into their own subdirectory, as
indicated by CODEBASE, this structure might improve the way a Web site is organized, but
there's no other reason why using CODEBASE is better than omitting it. The choice is a
matter of personal preference.
Q What happens if the height and width
specified for an applet don't leave enough room for the information that is
displayed in the paint() method?
A The
information will be drawn off-screen beyond the edges of the applet window and
won't be visible at any point while the applet runs. Choosing the right
dimensions for an applet is largely a matter of trial-and-error until you find
the right size for both the HEIGHT and WIDTH attributes of the <APPLET> tag. Fortunately, you can
change the Web page's HTML without having to recompile the Java program.
Quiz
The following questions test your knowledge of applets.
Questions
What type of argument is
used with the paint( method?
(a) A Graphics object
(b) A Boolean variable
(c) None
2. Which method is handled right
before an applet finishes running?
(a) decline(
(b) destroy()
(c) demise()
3. Why can't all variables needed in
an applet be created inside the init( method?
(a) The scope of the variables would be limited to the method only.
(b) Federal legislation prohibits it.
(c) They can be created there without
any problems.
Answers
a.
The Graphics object keeps track of the
behavior and attributes needed to display things on-screen in the applet
window.
2. b.
3. a. Variables that are used in more than one method of a class should be
created right after the class statement but before any methods begin.
Activities
You can apply your applet programming knowledge with the following activity:
Create an applet that displays the values of an array in the applet window and adds one to some of the values each time the applet is repainted. Drag other windows atop the running version of this program to force it to require repainting. This exercise demonstrates how the paint( method is called for behind the scenes.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 768
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved