HTML is a markup language that presents static documents on the Web. It uses tags to instruct the Web browser how to render a Web page and contains a tag called <applet> that incorporates applets into a Web page.
The following HTML file named WelcomeApplet.html invokes the WelcomeApplet.class:
<html> <head> <title> Welcome Java Applet </title> </head> <body> <applet code = "WelcomeApplet.class" width = 350 height = 200 > </applet> </body> </html>
A tag is an instruction to the Web browser. The browser interprets the tag and decides how to display or otherwise treat the subsequent contents of the HTML document. Tags are enclosed inside brackets. The first word in a tag, called the tag name , describes tag functions. Tags can have additional attributes, sometimes with values after an equals sign, which further define the tag's action. For example, in the preceding HTML file, <applet> is the tag name, and code , width , and height are the attributes. The width and height attributes specify the rectangular viewing area of the applet.
Most tags have a start tag and a corresponding end tag . The tag has a specific effect on the region between the start tag and the end tag. For example, <applet...>...</applet> tells the browser to display an applet. An end tag is always the start tag's name preceded by a slash.
An HTML document begins with the <html> tag, which declares that the document is written in HTML. Each document has two parts , a head and a body , defined by <head> and <body> tags, respectively. The head part contains the document title, using the <title> tag and other information the browser can use when rendering the document, and the body part contains the actual contents of the document. The header is optional. For more information, refer to Supplement VI.A, "HTML and XHTML Tutorial."
The complete syntax of the <applet> tag is as follows :
<applet [ codebase = applet_url ] code = classfilename.class width = applet_viewing_width_in_pixels height = applet_viewing_height_in_pixels [ archive = archivefile ] [ vspace = vertical_margin ] [ hspace = horizontal_margin ] [ align = applet_alignment ] [ alt = alternative_text ] > < param name = param_name1 value = param_value1> < param name = param_name2 value = param_value2> ... < param name = param_name3 value = param_value3> </applet>
The code , width , and height attributes are required; all the others are optional. The <param> tag is introduced in §16.6, "Passing Strings to Applets." The other attributes are explained below.
codebase specifies a base where your classes are loaded. If this attribute is not used, the Web browser loads the applet from the directory in which the HTML page is located. If your applet is located in a different directory from the HTML page, you must specify the applet _ url for the browser to load the applet. This attribute enables you to load the class from anywhere on the Internet. The classes used by the applet are dynamically loaded when needed.
archive instructs the browser to load an archive file that contains all the class files needed to run the applet. Archiving allows the Web browser to load all the classes from a single compressed file at one time, thus reducing loading time and improving performance. To create archives, see §16.12, "Packaging and Deploying Java Projects."
vspace and hspace specify the size , in pixels, of the blank margin to pad around the applet vertically and horizontally.
align specifies how the applet will be aligned in the browser. One of nine values is used: left , right , top , texttop , middle , absmiddle , baseline , bottom , or absbottom.
alt specifies the text to be displayed in case the browser cannot run Java.
You can test the applet using the applet viewer utility, which can be invoked from the DOS prompt using the appletviewer command from c:\book , as shown in Figure 16.2. Its output is shown in Figure 16.3.
Applets are eventually displayed in a Web browser. Using the applet viewer, you do not need to start a Web browser. The applet viewer functions as a browser. It is convenient for testing applets during development. However, you should also test the applets from a Web browser before deploying them on a Web site. To display an applet from a Web browser, open the applet's HTML file (e.g., WelcomeApplet.html). Its output is shown in Figure 16.4.
To make your applet accessible on the Web, you need to store the WelcomeApplet.class and WelcomeApplet.html on a Web server. You can view the applet from an appropriate URL. For example, I have uploaded these two files on Web server www.cs.armstrong.edu/ . As shown in Figure 16.5, you can access the applet from www.cs.armstrong.edu/liang/intro6e/book/WelcomeApplet.html .
This example writes an applet that computes loan payments. The applet enables the user to enter the interest rate, the number of years , and the loan amount. Clicking the Compute Payment button displays the monthly payment and the total payment, as shown in Figure 16.6. The applet is given in Listing 16.1.
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import javax.swing.border.TitledBorder; 5 6 public class LoanApplet extends JApplet { 7 // Declare and create text fields for interest rate 8 // year, loan amount, monthly payment, and total payment 9 private JTextField jtfAnnualInterestRate = new JTextField(); 10 private JTextField jtfNumberOfYears = new JTextField(); 11 private JTextField jtfLoanAmount = new JTextField(); 12 private JTextField jtfMonthlyPayment = new JTextField(); 13 private JTextField jtfTotalPayment = new JTextField(); 14 15 // Declare and create a Compute Payment button 16 private JButton jbtComputeLoan = new JButton( "Compute Payment" ); 17 18 /** Initialize user interface */ 19 public void init() { 20 // Set properties on the text fields 21 jtfMonthlyPayment.setEditable( false ); 22 jtfTotalPayment.setEditable( false ); 23 24 // Right align text fields 25 jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT); 26 jtfNumberOfYears.setHorizontalAlignment(JTextField.RIGHT); 27 jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT); 28 jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT); 29 jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT); 30 31 // Panel p1 to hold labels and text fields 32 JPanel p1 = new JPanel( new GridLayout( 5 , 2 )); 33 p1.add( new JLabel( "Annual Interest Rate" )); 34 p1.add(jtfAnnualInterestRate); 35 p1.add( new JLabel( "Number of Years" )); 36 p1.add(jtfNumberOfYears); 37 p1.add( new JLabel( "Loan Amount" )); 38 p1.add(jtfLoanAmount); 39 p1.add( new JLabel( "Monthly Payment" )); 40 p1.add(jtfMonthlyPayment); 41 p1.add( new JLabel( "Total Payment" )); 42 p1.add(jtfTotalPayment); 43 p1.setBorder( new 44 TitledBorder( "Enter interest rate, year and loan amount" )); 45 46 // Panel p2 to hold the button 47 JPanel p2 = new JPanel( new FlowLayout(FlowLayout.RIGHT)); 48 p2.add(jbtComputeLoan); 49 50 // Add the components to the applet 51 add(p1, BorderLayout.CENTER); 52 add(p2, BorderLayout.SOUTH); 53 54 // Register listener 55 jbtComputeLoan.addActionListener( new ButtonListener()); 56 } 57 58 /** Handle the Compute Payment button */ 59 private class ButtonListener implements ActionListener { 60 public void actionPerformed(ActionEvent e) { 61 // Get values from text fields 62 double interest = 63 Double.parseDouble(jtfAnnualInterestRate.getText()); 64 int year = 65 Integer.parseInt(jtfNumberOfYears.getText()); 66 double loanAmount = 67 Double.parseDouble(jtfLoanAmount.getText()); 68 69 // Create a loan object 70 Loan loan = new Loan(interest, year, loanAmount); 71 72 // Display monthly payment and total payment 73 jtfMonthlyPayment.setText(String.format( "%.2f" , 74 loan.getMonthlyPayment())); 75 jtfTotalPayment.setText(String.format( "%.2f" , 76 loan.getTotalPayment())); 77 } 78 } 79 } |
You need to use the public modifier for the LoanApplet ; otherwise, the Web browser cannot load it (line 6).
The init method initializes the user interface (lines 19 “56). The program overrides this method to create user-interface components (labels, text fields, and a button), and places them in the applet.
The only event handled is the Compute Payment button. When this button is clicked, the actionPerformed method gets the interest rate, number of years, and loan amount from the text fields. It then creates a Loan object (line 70) to obtain the monthly payment and the total payment. Finally, it displays the monthly and total payments in their respective text fields. The Loan class is responsible for computing the payments. This class was introduced in §7.15, "Case Study: The Loan Class."
To run the applet, embed it in the HTML file, as shown in Listing 16.2.
<!-- HTML code, this code is separated from the preceding Java code --> <html> <head> <title> Loan Applet </title> </head> <body> This is a loan calculator. Enter your input for interest, year, and loan amount. Click the "Compute Payment" button, you will get the payment information. <p> <applet code = "LoanApplet.class" width = 300 height = 150 alt = "You must have a Java 2-enabled browser to view the applet" > </applet> </body> </html> |
Tip
Many interesting applets are included in the JDK demo. To run them, change the directory to c:\Program Files\Java\jdk1. 5.0 \demo\applets Use the dir command to list the contents in the directory, as shown in Figure 16.7(a). Change to a subdirectory (e.g., using the command cd Animator ). There are one or several .html files in that directory for executing applets (e.g., example1.html ). In the command window, type the following to run the applet, as shown in Figure 16.7(b): appletviewer example1.html Figure 16.7. You can find applet examples in the JDK demo directory. |