Java Programming ... From the Grounds Up
Part 6
And finally...how to embed applets in your HTML pages!
A simple HTML file that loads the Variable Hello applet is shown in Figure 4. The applet specification begins with an <APPLET> tag, which has three modifiers. The code modifier specifies the name of the Java bytecode file VH.class. The width and height modifiers specify a default area which the browser should allocate in order to display the applet's graphics. Any number of <PARAM> tags may be specified between <APPLET>'s opening and closing tags. Our example shows a single parameter with the name who and the value "all you Java programmers". The name and value modifiers are always interpreted as strings.
FIGURE 4
The Variable hello HTML file.
<title>Variable Hello</title>
<'hr>
<applet code="VH.class" width=300 height=100>
<param name=who value="all you Java programmers">
</applet>
<hr>
<a href="VH.java">The source.</a>
Since this HTML specified a value for the who parameter, the getParameter() method will place its value in the String variable who. Had there had been no <PARAM> tag defining a who parameter, then getParameter() would have returned null, and the second line of code in init() would have given the variable who the predictable default value "world". The init() next calls the method getDocumentBase() from the java.net package, and stores the result in the local variable uwhere. This variable is of type URL, and will contain a description of this page's URL. A printable representation of the URL is obtained using the toString() method. Finally, init() constructs two greeting messages and places them in the class variables msg1 and msg2. msg1 contains the fixed string "Hello", followed by the value of who and another comma. msg2 reports the source of the greeting by combining "from" and the string form of the URL. As in Primes.java, "+" is used to join strings together.
The run() and paint() methods are both very simple. The run() method gets the default size of the applet using the preferredSize() method, and then calls resize(). This is a polite request to the browser to restore the applet's drawing area to 300x100, in case the window size has been modified in some way. run() then calls the Java method repaint(), which will arrange to completely redraw the applet's drawing area. By a series of circuitous internal steps, this call to repaint() will ultimately invoke the paint() method, which we have overridden. paint() is called with a Graphics context g as its argument. We can now use a number of methods in the Graphics class to alter the drawing area. Here, we will simply change the text color to blue and then draw the two Strings msg1 and msg2, one below the other. Figure 5 shows the resulting output using appletviewer, the Java applet viewer from the JDK.
This example is extremely simple, but is does have all the components required of a fully functioning applet. It does not have any user interaction, however. Figure 6 shows an upgraded version of the VH applet which will respond to a user's mouse click. The HTML file that loads it is shown in Figure 7.
FIGURE 6
The interactive version of the Variable Hello applet.
1: /**
2: A simple Java applet to issue an HTML-specified greeting,
3: with a tiny bit of user interaction
4: @author Mark C. Reynolds
5: @version 1.0
6: */
7:
8: import java.awt.*;
9: import java.net.*;
10:
11: public class VH2
extends java.applet.Applet implements Runnable {
12:
13: String msg1;
14: String msg2;
15: String imgnam = null;
16: Image img;
17: boolean doimg = false;
18:
19: public void init() {
20: String who;
21: String where;
22: URL uwhere;
23:
24: who = getParameter("who");
25: if ( who == null ) who = "world";
26: uwhere = getDocumentBase();
27: where = uwhere.toString();
28: imgnam = getParameter("image");
29: if ( imgnam != null ) {
30: img = getImage(uwhere, "image/" + imgnam + ".gif");
31: }
32: msg1 = "Hello, " + who + ",";
33: msg2 = "from " + where;
34: }
35:
36: public boolean mouseDown(Event e, int x, int y) {
37: doimg = true;
38: repaint();
39: return(true);
40: }
41:
42: public void paint(Graphics g) {
43: Dimension d = size();
44:
45: g.drawRect(0, 0, d.width - 1, d.height - 1);
46: g.setColor(Color.blue);
47: g.drawString(msg1, 10, 15);
48: g.drawString(msg2, 10, 30);
49: g.drawString("Click anywhere to see
mouse event tracking", 10, 45);
50: if ( doimg == true && imgnam != null ) {
51: g.drawImage(img, 10, 60, this);
52: g.setColor(Color.red);
53: g.drawString("Squeek!", 10, 70 + img.getHeight(this));
54: }
55: }
56:
57: public void run() {
58: resize(preferredSize());
59: repaint();
60: }
61: }
FIGURE 7
HTML for the Variable Interactive Hello page.
<title>Variable Interactive Hello</title>
<hr>
<applet code="VH2.class" width=300 height=300>
<param name=who value="all you Java programmers">
<param name=image value="mouse">
</applet>
<hr>
<a href="VH2.java">The source.</a>
Adding Interaction
This Variable Interactive Hello applet has init(), run() and paint() methods, as before. It also has a mouseDown() method, which overrides the built-in method of that name. The init() method for this VH2 class is almost the same as the init() method in VH, except that it also looks for a parameter named image. If it is found, then the class variable imgnam will hold its value. In this case, the init() method also attempts to access that image using the getImage() method. The first argument to that method is the URL of the current page, stored in uwhere; the second specifies a relative pathname for the image. Since our HTML gives the value of imgnam as "mouse," a file named mouse.gif in the subdirectory image will be retrieved, if possible.
The mouseDown() method is called whenever a mouse button has been pressed. This method sets the class variable doimg to true, and then calls repaint to redraw the applet. Note that doimg is initialized to false, and is only toggled to true in the event of a user mouse click. The method returns true to indicate that it has handled the event.
The paint() method used here is significantly different than in VH. It begins by determining the current size of the Applet's drawing area via a call to size(). It then uses the drawRect method of the Graphics class to draw a blank rectangle covering the entire drawing area (a quick-and-dirty way to clear it). As in VH, the applet then sets the text color to blue and prints the two greeting strings, followed by an invitation to the user to click anywhere. If the class variable doimg is true and the class variable imgnam is not null, then the image retrieved during the init() method will be displayed, followed by the message "Squeek!" in red. The method call img.getHeight(this) returns the height of the image. This is used in the calculation of the y coordinate of the "Squeek!" string, so that it will appear just below the mouse GIF.
Logically, how does this work? When the page is first loaded, init() is called, followed by run(). The run() method calls repaint(), which generates its own call to paint(). At this point, doimg will still have its initial value of false. Therefore, only the two greeting strings will be drawn, followed by the enticing invitation to click anywhere. The applet will then sit in an event loop, waiting for something to happen. If the user accepts the invitation and clicks within the applet's drawing area, then the mouseDown() method will be called by AWT's event handler. Our mouseDown() method will then set doimg to true and call repaint(). This forces a second pass through the paint() method. This time the three strings will again be drawn, but the image and the final red "Squeek!" will be displayed as well. The user has caused a GIF and a string to appear by clicking within the applet.
For More Information . . .
Even though this example uses less than 50 lines of code, it still manages to illustrate some of the interactive power of Java. One of Java's great advantages is that it incorporates many of the most common user interface, network and parsing tools within its extensive class hierarchy. For this reason it is possible to build up much more sophisticated applets without requiring vast amounts of code. In the second part of this article we will explore some of these capabilities in greater depth.
Until then, there are several places you can explore to learn more about Java. The ultimate resource is Sun's own Java home page, where documentation links lead to the Java Programmer's Manual, complete specifications for every class within the Java class hierarchy, and a specification for the Java Virtual machine, among other documents of interest. Netscape's home page also contains several interesting links to Java applet code and other Java resources.
One final note of caution: This examples in this article used the Beta 2 version of the Java language, classes and tools. When browsing the Web you will undoubtedly encounter earlier versions, including the Beta 1, "Pre-Beta" and Alpha-3 versions of Java. While the Beta and Pre-Beta versions are quite similar, the differences between the Alpha-3 version and the others are particularly severe. If you see HTML documents with an <APP> tag, or Java source attempting to import awt.* rather than java.awt.*, beware--these are no longer supported.
[ < Java Programming ... From the Grounds Up: Part 5 ] |
[ Java Programming ... From the Grounds Up: Part 1 > ] |
|