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
Applet Attributes for PositioningWhat 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.
Applet Attributes for CodeThe following applet attributes tell the browser how to locate the applet code; here are short descriptions.
NOTE
Applet Attributes for Java-Challenged ViewersIf 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 TagThe 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 AppletsJust 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
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
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 appletThis 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.java1. 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
|