The Applet HTML Tags and Attributes

   


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. The code, width, and height attributes are required. If any are missing, the browser cannot load your applet.

All 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>       <p>The next line of text is displayed under the auspices of Java:</p>       <applet code="NotHelloWorldApplet.class" width="100" height="100">          If your browser could show Java, you would see an applet here.       </applet>    </body> </html> 

NOTE

According to the HTML specification, the HTML tags and attributes such as applet can be in upper or lower case. We use lower case 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. Readers familiar with HTML will recognize that 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.

    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 text in 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 text in the current line.

    bottom

    Places the bottom of the applet at the bottom of the text in 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. Because 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


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 the codebase is not specified.

    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 is a URL for locating the class files. You can use an absolute URL, even to a different server. Most commonly, though, this is a relative URL that points to a subdirectory. For example, if the file layout looks like this:

    then you use the following tag in MyPage.html:

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

  • 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 because 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

    This tag lets you specify the name of a file that contains the serialized applet object. (An object is serialized when you write all its instance fields to a file. We discuss serialization in Chapter 12.) To display the applet, 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.

    NOTE

    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.)

    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 discuss this mechanism, called inter-applet communication, later in this chapter.

NOTE

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.


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 codetype attribute, you specify the nature of the object. For example, Java applets have a code type of application/java. Here is an object 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.

Use of Parameters to Pass 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 by 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");       . . .    }    . . . } 

NOTE

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. Because 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"));       . . .     } } 

NOTE

The strings used when you define the parameters with 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


This 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 parameter 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 weekly is more tedious.

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


 java.applet.Applet 1.0 

  • public String getParameter(String name)

    gets the value of a parameter defined with a param tag in the web page loading the applet. The string name 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 you can 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 Volume I - Fundamentals
    Core Java(TM) 2, Volume I--Fundamentals (7th Edition) (Core Series) (Core Series)
    ISBN: 0131482025
    EAN: 2147483647
    Year: 2003
    Pages: 132

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