The Applet HTML Tags and Attributes

   

Core Java™ 2: Volume I - Fundamentals
By Cay S. Horstmann, Gary Cornell
Table of Contents
Chapter 10.  Deploying Applets and Applications


In its most basic form, an example for using the applet tag looks like this:

 <applet code="NotHelloWorldApplet.class"    width="300" height="100"> 

As you have seen, the code attribute gives the name of the class file and must include the .class extension; the width and height attributes size the window that will hold the applet. Both are measured in pixels. You also need a matching </applet> tag that marks the end of the HTML tagging needed for an applet. The text between the <applet> and </applet> tags is displayed only if the browser cannot show applets. These tags are required. If any are missing, the browser cannot load your applet.

All of this information would usually be embedded in an HTML page that, at the very least, might look like this:

 <html> <head> <title>NotHelloWorldApplet</title> </head> <body> The next line of text is displayed under the auspices of Java: <applet code="NotHelloWorldApplet.class"    width="100" height="100"> If your browser could show Java, you would see an applet here. </applet> </body> </html> 

graphics/notes_icon.gif

According to the HTML specification, the HTML tags and attributes such as applet can be in upper- or lowercase. We use lowercase because that is the recommendation of the newer XHTML specification. However, the name of the applet class is case-sensitive! The letter case may be significant in other attributes, such as names of JAR files, if the web server file system is case sensitive.

Applet Attributes for Positioning

What follows are short discussions of the various attributes that you can (or must) use within the applet tag to position your applet. For those familiar with HTML, many of these attributes are similar to those used with the IMG tag for image placement on a web page.

  • width, height

    These attributes are required and give the width and height of the applet, measured in pixels. In the applet viewer, this is the initial size of the applet. You can resize any window that the applet viewer creates. In a browser, you cannot resize the applet. You will need to make a good guess about how much space your applet requires to show up well for all users.

  • align

    This attribute specifies the alignment of the applet. There are two basic choices. The applet can be a block with text flowing around it, or the applet can be inline, floating inside a line of text as if it were an oversized text character. The first two values (left and right) make the text flow around the applet. The others make the applet flow with the text.

The choices are described in Table 10-1.

Table 10-1. Applet positioning attributes

Attribute

What It Does

left

Places the applet at the left margin of the page. Text that follows on the page goes in the space to the right of the applet.

right

Places the applet at the right margin of the page. Text that follows on the page goes in the space to the left of the applet.

bottom

Places the bottom of the applet at the bottom of the text in the current line.

top

Places the top of the applet with the top of the current line.

texttop

Places the top of the applet with the top of the text in the current line.

middle

Places the middle of the applet with the baseline of the current line.

absmiddle

Places the middle of the applet with the middle of the current line.

baseline

Places the bottom of the applet with the baseline of the current line.

absbottom

Places the bottom of the applet with the bottom of the current line.

vspace, hspace

These optional attributes specify the number of pixels above and below the applet (vspace) and on each side of the applet (hspace).

Figure 10-6 shows all alignment options for an applet that floats with the surrounding text. The vertical bar at the beginning of each line is an image. Since the image is taller than the text, you can see the difference between alignment with the top or bottom of the line and the top or bottom of the text.

Figure 10-6. Applet alignment

graphics/10fig06.gif

Applet Attributes for Code

The following applet attributes tell the browser how to locate the applet code; here are short descriptions.

  • code

    This attribute gives the name of the applet's class file. This name is taken relative to the codebase (see below) or relative to the current page.

    If you use a relative path name, then the path name must match the package of the applet class. For example, if the applet class is in the package com.mycompany, then the attribute is code="com/mycompany/MyApplet.class". The alternative code="com.mycompany.MyApplet.class" is also permitted. But you cannot use absolute path names here. Use the codebase attribute if your class file is located elsewhere.

    The code attribute specifies only the name of the class that contains the applet class. Of course, your applet may contain other class files. Once the browser's class loader loads the class containing the applet, it will realize that it needs more class files, and will load them.

    Either the code or the object attribute (see below) is required.

  • codebase

    This optional attribute tells the browser that your class files are found below the directory indicated in the codebase attribute. For example, if an applet called CalculatorApplet is in the directory MyApplets, and the MyApplets directory is below the location of the web page, you would use:

     <applet code="CalculatorApplet.class" codebase="MyApplets"    width="100" height="150"> 

    In other words, the file layout looks like this:

     aDirectory/    CalculatorApplet.html    MyApplets/       CalculatorApplet.class 
  • archive

    This optional attribute lists the Java archive file or files containing classes and other resources for the applet. (See the section on JAR files later in this chapter for more on Java archive files.) These files are fetched from the web server before the applet is loaded. This technique speeds up the loading process significantly since only one HTTP request is necessary to load a JAR file that contains many smaller files. The JAR files are separated by commas. For example:

     <applet code="CalculatorApplet.class" archive=    "CalculatorClasses.jar,corejava/CoreJavaClasses.jar"    width="100" height="150"> 
  • object

    As another way to specify the applet class file, you can specify the name of a file that contains the serialized applet object, but browsers vary in support of this attribute. You will definitely need to use the Java Plug-In if you want to use this feature. (An object is serialized when you write all its data fields to a file. We will discuss serialization in Chapter 12.) The object is deserialized from the file to return it to its previous state. When you use this attribute, the init method is not called, but the applet's start method is called. Before serializing an applet object, you should call its stop method. This feature is useful for implementing a persistent browser that automatically reloads its applets and has them return to the same state that they were in when the browser was closed. This is a specialized feature, not normally encountered by web page designers.

    Either code or object must be present in every applet tag. For example,

     <applet object="CalculatorApplet.ser"    width="100" height="150"> 
  • name

    Scripters will want to give the applet a name attribute that they can use to refer to the applet when scripting. Both Netscape and Internet Explorer let you call methods of an applet on a page through JavaScript. This is not a book on JavaScript, so we only give you a brief idea of the code that is required to call Java code from JavaScript.

graphics/notes_icon.gif

JavaScript is a scripting language that can be used inside web pages, invented by Netscape and originally called LiveScript. It has little to do with Java, except for some similarity in syntax. It was a marketing move to call it JavaScript. A subset (with the catchy name of ECMAScript) is standardized as ECMA-262. But, to nobody's surprise, Netscape and Microsoft support incompatible extensions of that standard in their browsers. For more information on JavaScript, we recommend the book JavaScript: The Definitive Guide by David Flanagan, published by O'Reilly & Associates.

To access an applet from JavaScript, you first have to give it a name.

 <applet code="CalculatorApplet.class"    width="100" height="150"    name="calc" </applet> 

You can then refer to the object as document.applets.appletname. For example,

 var calcApplet = document.applets.calc; 

Through the magic of the integration between Java and JavaScript that both Netscape and Internet Explorer provide, you can call applet methods:

 calcApplet.clear(); 

(Our calculator applet doesn't have a clear method; we just want to show you the syntax.)

graphics/notes_icon.gif

In http://www.javaworld.com/javatips/jw-javatip80.html, Francis Lu uses JavaScript-to-Java communication to solve an age-old problem: to resize an applet so that it isn't bound by hardcoded width and height attributes. This is a good example of the integration between Java and JavaScript. It also shows how messy it is to write JavaScript that works on multiple browsers.

The name attribute is also essential when you want two applets on the same page to communicate with each other directly. You specify a name for each current applet instance. You pass this string to the getApplet method of the AppletContext class. We will discuss this mechanism, called inter-applet communication, later in this chapter.

Applet Attributes for Java-Challenged Viewers

If a web page containing an applet tag is viewed by a browser that is not aware of Java applets, then the browser ignores the unknown applet and param tags. All text between the <applet> and </applet> tags is displayed by the browser. Conversely, Java-aware browsers do not display any text between the <applet> and </applet> tags. You can display messages inside these tags for those poor folks that use a prehistoric browser. For example,

 <applet code="CalculatorApplet.class"    width="100" height="150"> If your browser could show Java, you would see a calculator here. </applet> 

Of course, nowadays most browsers know about Java, but Java may be deactivated, perhaps by the user or by a paranoid system administrator. You can then use the alt attribute to display a message to these unfortunate souls.

 <applet code="CalculatorApplet.class"    width="100" height="150"    alt="If your browser could show Java, you would see    a calculator here"> 

The object Tag

The object tag is part of the HTML 4.0 standard, and the W3 consortium suggests that people use it instead of the applet tag. There are 35 different attributes to the object tag, most of which (such as onkeydown) are relevant only to people writing Dynamic HTML. The various positioning attributes such as align and height work exactly as they did for the applet tag. The key attribute in the object tag for your Java applets is the classid attribute. This attribute specifies the location of the object. Of course, object tags can load different kinds of objects, such as Java applets or ActiveX components like the Java Plug-In itself. In the code attribute, you specify the nature of the object. For example, Java applets have a code type of application/java. Here is an objecct tag to load a Java applet:

 <object    codetype="application/java"    class    width="100" height="150"> 

Note that the classid attribute can be followed by a codebase attribute that works exactly as it did with the applet tag.

Passing Information to Applets

Just as applications can use command-line information, applets can use parameters that are embedded in the HTML file. This is done via the HTML tag called param along with attributes that you define. For example, suppose you want to let the web page determine the style of the font to use in your applet. You could use the following HTML tags:

 <applet code="FontParamApplet.class" width="200" height="200"> <param name="font" value="Helvetica"/> </applet> 

You then pick up the value of the parameter, using the getParameter method of the Applet class, as in the following example:

 public class FontParamApplet extends JApplet {    public void init()    {       String fontName = getParameter("font");       . . .    }    . . . } 

graphics/notes_icon.gif

You can call the getParameter method only in the init method of the applet, not in the constructor. When the applet constructor is executed, the parameters are not yet prepared. Since the layout of most nontrivial applets is determined by parameters, we recommend that you don't supply constructors to applets. Simply place all initialization code into the init method.

Parameters are always returned as strings. You need to convert the string to a numeric type if that is what is called for. You do this in the standard way by using the appropriate method, such as parseInt of the Integer class.

For example, if we wanted to add a size parameter for the font, then the HTML code might look like this:

 <applet code="FontParamApplet.class" width="200" height="200"> <param name="font" value="Helvetica"/> <param name="size" value="24"/> </applet> 

The following source code shows how to read the integer parameter.

 public class FontParamApplet extends JApplet {    public void init()    {       String fontName = getParameter("font");       int fontSize = Integer.parseInt(getParameter("size"));       . . .     } } 

graphics/notes_icon.gif

The strings used when you define the parameters via the param tag and those used in the getParameter method must match exactly. In particular, both are case sensitive.

In addition to ensuring that the parameters match in your code, you should find out whether or not the size parameter was left out. You do this with a simple test for null. For example:

 int fontsize; String sizeString = getParameter("size"); if (sizeString == null) fontSize = 12; else fontSize = Integer.parseInt(sizeString); 

Here is a useful applet that uses parameters extensively. The applet draws a bar chart, shown in Figure 10-7.

Figure 10-7. A chart applet

graphics/10fig07.gif

The applet takes the labels and the heights of the bars from the param values in the HTML file. Here is what the HTML file for Figure 10-7 looks like:

 <applet code="Chart.class" width="400" height="300"> <param name="title" value="Diameters of the Planets"/> <param name="values" value="9"/> <param name="name.1" value="Mercury"/> <param name="name.2" value="Venus"/> <param name="name.3" value="Earth"/> <param name="name.4" value="Mars"/> <param name="name.5" value="Jupiter"/> <param name="name.6" value="Saturn"/> <param name="name.7" value="Uranus"/> <param name="name.8" value="Neptune"/> <param name="name.9" value="Pluto"/> <param name="value.1" value="3100"/> <param name="value.2" value="7500"/> <param name="value.3" value="8000"/> <param name="value.4" value="4200"/> <param name="value.5" value="88000"/> <param name="value.6" value="71000"/> <param name="value.7" value="32000"/> <param name="value.8" value="30600"/> <param name="value.9" value="1430"/> </applet> 

You could have set up an array of strings and an array of numbers in the applet, but there are two advantages to using the param mechanism instead. You can have multiple copies of the same applet on your web page, showing different graphs: just put two applet tags with different sets of parameters on the page. And you can change the data that you want to chart. Admittedly, the diameters of the planets will stay the same for quite some time, but suppose your web page contains a chart of weekly sales data. It is easy to update the web page because it is plain text. Editing and recompiling a Java file on a weekly basis is more tedious.

In fact, there are commercial Java beans that make much fancier graphs than the one in our chart applet. If you buy one, you can drop it into your web page and feed it parameters without ever needing to know how the applet renders the graphs.

Example 10-5 is the source code of our chart applet. Note that the init method reads the parameters, and the paintComponent method draws the chart.

Example 10-5 Chart.java
   1. import java.awt.*;   2. import java.awt.font.*;   3. import java.awt.geom.*;   4. import javax.swing.*;   5.   6. public class Chart extends JApplet   7. {   8.    public void init()   9.    {  10.       String v = getParameter("values");  11.       if (v == null) return;  12.       int n = Integer.parseInt(v);  13.       double[] values = new double[n];  14.       String[] names = new String[n];  15.       int i;  16.       for (i = 0; i < n; i++)  17.       {  18.          values[i] = Double.parseDouble  19.             (getParameter("value." + (i + 1)));  20.          names[i] = getParameter("name." + (i + 1));  21.       }  22.  23.       Container contentPane = getContentPane();  24.       contentPane.add(new ChartPanel(values, names,  25.          getParameter("title")));  26.    }  27. }  28.  29. /**  30.    A panel that draws a bar chart.  31. */  32. class ChartPanel extends JPanel  33. {  34.    /**  35.        Constructs a ChartPanel.  36.        @param v the array of values for the chart  37.        @param n the array of names for the values  38.        @param t the title of the chart  39.    */  40.    public ChartPanel(double[] v, String[] n, String t)  41.    {  42.       names = n;  43.       values = v;  44.       title = t;  45.    }  46.  47.    public void paintComponent(Graphics g)  48.    {  49.       super.paintComponent(g);  50.       Graphics2D g2 = (Graphics2D)g;  51.  52.       // compute the minimum and maximum values  53.       if (values == null) return;  54.       double minValue = 0;  55.       double maxValue = 0;  56.       for (int i = 0; i < values.length; i++)  57.       {  58.          if (minValue > values[i]) minValue = values[i];  59.          if (maxValue < values[i]) maxValue = values[i];  60.       }  61.       if (maxValue == minValue) return;  62.  63.       int panelWidth = getWidth();  64.       int panelHeight = getHeight();  65.  66.       Font titleFont = new Font("SansSerif", Font.BOLD, 20);  67.       Font labelFont = new Font("SansSerif", Font.PLAIN, 10);  68.  69.       // compute the extent of the title  70.       FontRenderContext context = g2.getFontRenderContext();  71.       Rectangle2D titleBounds  72.          = titleFont.getStringBounds(title, context);  73.       double titleWidth = titleBounds.getWidth();  74.       double top = titleBounds.getHeight();  75.  76.       // draw the title  77.       double y = -titleBounds.getY(); // ascent  78.       double x = (panelWidth - titleWidth) / 2;  79.       g2.setFont(titleFont);  80.       g2.drawString(title, (float)x, (float)y);  81.  82.       // compute the extent of the bar labels  83.       LineMetrics labelMetrics  84.          = labelFont.getLineMetrics("", context);  85.       double bottom = labelMetrics.getHeight();  86.  87.       y = panelHeight - labelMetrics.getDescent();  88.       g2.setFont(labelFont);  89.  90.       // get the scale factor and width for the bars  91.       double scale = (panelHeight - top - bottom)  92.          / (maxValue - minValue);  93.       int barWidth = panelWidth / values.length;  94.  95.       // draw the bars  96.       for (int i = 0; i < values.length; i++)  97.       {  98.          // get the coordinates of the bar rectangle  99.          double x1 = i * barWidth + 1; 100.          double y1 = top; 101.          double height = values[i] * scale; 102.          if (values[i] >= 0) 103.             y1 += (maxValue - values[i]) * scale; 104.          else 105.          { 106.             y1 += maxValue * scale; 107.             height = -height; 108.          } 109. 110.          // fill the bar and draw the bar outline 111.          Rectangle2D rect = new Rectangle2D.Double(x1, y1, 112.             barWidth - 2, height); 113.          g2.setPaint(Color.RED); 114.          g2.fill(rect); 115.          g2.setPaint(Color.BLACK); 116.          g2.draw(rect); 117. 118.          // draw the centered label below the bar 119.          Rectangle2D labelBounds 120.             = labelFont.getStringBounds(names[i], context); 121. 122.          double labelWidth = labelBounds.getWidth(); 123.          x = i * barWidth + (barWidth - labelWidth) / 2; 124.          g2.drawString(names[i], (float)x, (float)y); 125.       } 126.    } 127. 128.    private double[] values; 129.    private String[] names; 130.    private String title; 131. } 

java.applet.Applet 1.0

graphics/api_icon.gif
  • public String getParameter(String name)

    gets a parameter defined with a param directive in the web page loading the applet. The string is case sensitive.

  • public String getAppletInfo()

    is a method that many applet authors override to return a string that contains information about the author, version, and copyright of the current applet. You need to create this information by overriding this method in your applet class.

  • public String[][] getParameterInfo()

    is a method that many applet authors override to return an array of param tag options that this applet supports. Each row contains three entries: the name, the type, and a description of the parameter. Here is an example:

     "fps", "1-10", "frames per second" "repeat", "boolean", "repeat image loop?" "images", "url", "directory containing images" 


       
    Top
     



    Core Java 2(c) Volume I - Fundamentals
    Building on Your AIX Investment: Moving Forward with IBM eServer pSeries in an On Demand World (MaxFacts Guidebook series)
    ISBN: 193164408X
    EAN: 2147483647
    Year: 2003
    Pages: 110
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net