Previous Page TOC Index Next Page Home


14

From JavaScript to Java—Looking into the Future

Having mastered the essentials of JavaScript, it should be clear that JavaScript is a powerful tool for extending the functionality of basic HTML documents and creating sophisticated interactive applications.

Nonetheless, the question remains: How do I do more? Can I move beyond JavaScript and extend its power?

In this chapter, we take a look at the future relationship between JavaScript and Java and how you can quickly and easily add Java applets to your pages today.

You'll learn about the following:

Integrating Java into JavaScript—The Future applet Object

When Sun and Netscape announced the creation JavaScript in late 1995, they made a lot of noise about the role of JavaScript in gluing Java into Web pages.

Java applets, because they exist outside the context of the Web page itself, are unable to interact with the type of document, form, and window objects that JavaScript can work with. Java applets are simply assigned a space in the current page, like images are given a particular rectangle, and then they do their thing in that space.

Any interaction with the user requires the applet to provide its own alternatives to the HTML forms and links that JavaScript can so readily work with. Given this, JavaScript's role is supposed to become the link. By having access to all the document and browser objects, as well as having objects which provide hooks into each Java applet in a page, a JavaScript script can play the role of middle-man and cause information generated by user or browser events outside the applet to be passed to any applet.

Pretty powerful stuff, overall.

In its current form, however, JavaScript provides no means by which to interact with Java applets. The version of JavaScript built into version 2.0 of Netscape Navigator doesn't provide the applet object. This is scheduled for inclusion in the next release of Navigator— due out later in 1996.

Still, this doesn't prevent JavaScript-enabled Web pages from taking advantage of Java applets and even from performing some basic manipulations that would seem to the user to be interacting with Java applets.

Basic Java Concepts

In order to be able to easily use applets other people have written in your Web pages, it is necessary to understand several fundamental things about Java.

First, Java is compiled. In order to build your own Java applets or to compile source code provided by friendly folk on the Web and in Usenet newsgroups, it is necessary to have a Java compiler.

Presently, the Java development kit is available for SPARC-based hardware running the Solaris operating system and 32-bit Windows platforms (namely, Windows 95 and Windows NT). The compiler and related files and documentation are available at

http://www.javasoft.com/

Other groups have ported the Java Development Kit to other platforms, such as Linux and the Mac OS.

Once the source code for an applet is compiled, it becomes a class file. Class files are not source code and contain objects that can be used in other programs or applets you build. The class file for a Java applet is what is downloaded to the browser and executed when a user loads a page containing the applet.

Presently, there are several large archives of freely-available applets which often include source code or even downloadable Java binary files. If you want to use these applets, you can download the source code and compile them yourself or download the actual class files. Information about using the Java compiler is included in the documentation at the Java Web page.

The leading archives can be found at this site:

http://www.gamelan.com/

and at the Java Web page itself.


In looking though these archives, you will notice both Alpha and Beta applets (supported by Navigator 2.0). There have been two main stages in the development of Java. The alpha applets are supported on the HotJava browser for Solaris and 32-bit Windows. The beta applets and applets written to the final release API are supported by Netscape. Sun is encouraging Java developers to move from Alpha applets to the current specification. We will be discussing the current specification throughout this chapter.

In order to understand how to go about obtaining and preparing to use existing applets, you are going to prepare to use the Growing Text applet by Jamie Hall, which you will use for the rest of the chapter. This applet animates any string of text and causes it to grow from very small to very large. The page author can control several different options including color, font, and delay.

I am assuming that you have downloaded the development kit (which includes the compiler) from Sun's Java home page and have followed the installation instructions. The development kit is available for several platforms including Windows 95, the Mac OS, and Solaris. Navigator can run Java applets in its 32-bit Windows version, its UNIX versions and the Mac version.

The Growing Text applet can be found on the Web at this site:

http://www1.mhv.net/~jamihall/java/GrowingText/GrowingText.html

You should download the source code, which looks like Listing 14.1 (remember—this is Java code and not a JavaScript script).

Input

/*

 * GrowingText

 *

 * Feel free to re-use any part of this code.

 *

 * Jamie Hall, [email protected]  1/9/96

 *

 * Jamie Hall 2/2/96 - Added blur parameter

 */

/*

   Takes text, delay, fontName, fontBold, fontItalic, bgColor,

   and fgColor as parameters.  The following are the defaults:

   text        -   String displayed in applet      -  Growing Text

   delay       -   Milliseconds between updates    -  500

   fontName    -   Font style                      -  TimesRoman

   fontBold    -   Font boldness                   -  true

   fontItalic  -   Font italics                    -  false

   bgColor     -   Background color (hex. number)  -  light Gray

   fgColor     -   Foreground color (hex. number)  -  black

   blur        -   Blurring effect                 -  false

   Note: 'random' can be used as the background or foreground color

   to generate a random color on each update.

  */

import java.awt.*;

import java.applet.*;

public class GrowingText extends Applet implements Runnable {

  String fontName = "TimesRoman", text = "Growing Text", bgColor, fgColor;

  Thread killme = null;

  boolean threadSuspended = false, blur = false;

  int fonts[] = { 8, 12, 14, 18, 24, 36 };

  int delay = 500, numFonts = 6, fontIndex = 0, fontStyle;

  Font appFont;

  public void init() {

    String param;

    boolean fontBold = true, fontItalic = false;

    param = getParameter("text");

    if (param != null) { text = param; }

    param = getParameter("delay");

    if (param != null) { delay = Integer.parseInt(param); }

    param = getParameter("fontName");

    if (param != null) { fontName = param; }

    param = getParameter("fontBold");

    if (param != null) { fontBold = param.equals("true"); }

    param = getParameter("fontItalic");

    if (param != null) { fontItalic = param.equals("true"); }

    fontStyle = (fontBold ? Font.BOLD : Font.PLAIN) +

      (fontItalic ? Font.ITALIC : Font.PLAIN);

    bgColor = getParameter("bgColor");

    if (bgColor == null) { bgColor = "Color.lightGray"; }

    setBackground(colorFromString(bgColor, Color.lightGray));

    fgColor = getParameter("fgColor");

    if (fgColor == null) { fgColor = "Color.black"; }

    setForeground(colorFromString(fgColor, Color.black));

    param = getParameter("blur");

    if (param != null) { blur = param.equals("true"); }

    /* Resize applet to fit string with largest font.

       Only works in JDK appletviewer, Netscape ignores it */

    /* FontMetrics fm = getFontMetrics(new Font(fontName, fontStyle, fonts[numFonts-1]));

resize(fm.stringWidth(s) + 20, appFont.getSize() + 20); */

  }

  public void start() {

    if (killme == null) {

      killme = new Thread(this);

      killme.start();

    }

  }

  public void stop() {

    if (killme != null) {

      killme.stop();

      killme = null;

    }

  }

  public void run() {

    while (killme != null) {

      repaint();

      try { Thread.sleep(delay); } catch (InterruptedException e) {};

    }

    killme = null;

  }

  public void update(Graphics g) {

    if (blur) {

      if (fontIndex > numFonts - 1 ) {

        g.clearRect(0, 0, size().width, size().height);

      }

      paint(g);

    } else {

      g.clearRect(0, 0, size().width, size().height);

      paint(g);

    }

  }

  public void paint(Graphics g) {

    if (bgColor.equalsIgnoreCase("random")) {

      setBackground(colorFromString(bgColor, Color.lightGray));

    }

    if (fgColor.equalsIgnoreCase("random")) {

      setForeground(colorFromString(fgColor, Color.black));

    }

    if (fontIndex > numFonts - 1 ) {

      fontIndex = 0;

    }

    g.setFont(appFont = new Font(fontName, fontStyle, fonts[fontIndex++]));

    FontMetrics fm = getFontMetrics(appFont);

    g.drawString(text, (size().width - fm.stringWidth(text))/2,

      (size().height/2)+10);

  }

  public boolean mouseDown(Event evt, int x, int y) {

    if (threadSuspended) {

      killme.resume();

    } else {

      killme.suspend();

    }

    threadSuspended = !threadSuspended;

    return true;

  }

  public Color colorFromString(String str, Color defaultColor) {

    if (str.equalsIgnoreCase("random")) {

      return new Color((int)(Math.random() * 256),  (int)(Math.random() * 256), (int)(Math.random() * 256));

} else {

      try {

        Integer i = Integer.valueOf(str, 16);

        return new Color(i.intValue());

      } catch (NumberFormatException e) {

         return defaultColor;

      }

    }

  }

  public String getAppletInfo() {

    return "GrowingText effect by Jamie M. Hall, 1996";

  }

}

Output

The demonstration page for this applet looks like Figure 14.1.


Figure 14.1. The Growing Text applet.

End of Output

Once you have the source code, the next step is to compile it. On Windows 95 or NT systems, this involves running the program javac (which is the compiler). For instance javac GrowingText.java will compile the Java source code file you downloaded. The result of this process should be a file called GrowingText.class. The .class files are Java binaries, and this is the actual executable applet used by the browser.

Incorporating Java Applets in HTML: The APPLET Tag

Including a JavaScript applet in an HTML file requires the use of the APPLET tag. The APPLET tag specifies the URL of the Java class file for the applet and tells the browser what size rectangular space to set aside for use by the applet. This is done using the attributes outlined in Table 14.1.

Name


Description


CODE

Specifies the URL binary class file for the applet (this can be relative to the base URL specified with the CODEBASE attribute).

CODEBASE

Specifies the base URL for applets (this points to the directory containing applet code).

WIDTH

Specifies the width of the rectangle set aside for the applet.

HEIGHT

Specifies the height of the rectangle set aside for the applet.

The APPLET tag is a container tag. Any text between the opening and closing tags will be displayed by browsers that don't support the APPLET tag (that is, which don't support the beta version of Java).

In addition to defining the space in which the APPLET is able to operate, you can also pass parameters—which can be thought of as arguments—to the applet using the PARAM tag. You can include as many PARAM tags—which define name-value pairs for the parameters—as you want between the opening and closing APPLET tags. The PARAM tag takes the form

<PARAM NAME="nameOfParameter" VALUE="valuePassedForParameter">

Using the GrowingText applet, which you compiled in Listing 14.1, you can now build a simple Web page that displays the applet in a 500x200 pixel rectangle with the words "Java Really Works" as the text used by the applet.

As you can see in the source code for the applet (Listing 14.1), there are several parameters available to you to set:

Takes text, delay, fontName, fontBold, fontItalic, bgColor,

   and fgColor as parameters.  The following are the defaults:

   text        -   String displayed in applet      -  Growing Text

   delay       -   Milliseconds between updates    -  500

   fontName    -   Font style                      -  TimesRoman

   fontBold    -   Font boldness                   -  true

   fontItalic  -   Font italics                    -  false

   bgColor     -   Background color (hex. number)  -  light Gray

   fgColor     -   Foreground color (hex. number)  -  black

   blur        -   Blurring effect                 -  false

   Note: 'random' can be used as the background or foreground color

   to generate a random color on each update.

For your Web page, you will use a delay of 250 milliseconds and bold type to test the blurring effect. Listing 14.2 shows how to combine the applet into a Web page.

Input

<HTML>

<HEAD>

<TITLE>Example 14.2</TITLE>

</HEAD>

<BODY>

<H1>Java Applet Example</H1>

<APPLET CODE="GrowingText.class" WIDTH=500 HEIGHT=200>

<PARAM NAME="text" VALUE="Java Really Works">

<PARAM NAME="delay" VALUE="250">

<PARAM NAME="bold" VALUE="true">

<PARAM NAME="blur" VALUE="true">

</APPLET>

</BODY>

</HTML>

Output

Figure 14.2 illustrates the effects of the script.


Figure 14.2. The APPLET tag lets you define the space available to the applet.

End of Output

Analysis

There are several things to notice in this example. First, there are default values for many of the parameters, so you don't actually need any parameters to get the applet to work. The parameters are like optional arguments. In this case, you can use as few or as many as you like.

The Java applet continues to run until you leave the page or close Netscape.

Working with Java Today

Although the applet object is not available in the current version of JavaScript, it is still possible to create limited interaction between applets and the browser environment using JavaScript.

For instance, with JavaScript's ability to dynamically generate HTML code, a form in one frame could easily reload a Java applet in another frame, with new parameters.

While this is not truly interacting with an applet while it is loaded and executing, it can produce the appearance that the applet is better integrated into a Web application.

To demonstrate how dynamically written HTML can be used to change the state of an applet in another frame, let's build a simple testing program for the GrowingText applet.

This program should enable the user to enter a string, select options from checkboxes, and fill in fields. When the user clicks on a Test button, the applet should be reloaded in a second frame with the new parameters. Listings 14.3 through 14.5 are the source code for this application.

Input

<!-- SOURCE CODE OF PARENT FRAMESET -->

<FRAMESET ROWS="50%,*">

  <FRAME SRC="javatest.html" NAME="form">

  <FRAME SRC="blank.html" NAME="applet">

</FRAMESET>

Listings 14.4 and 14.5 are the source code for javatest.html that provides a form to test different parameters of the applet and the code to display it.

Input

<!-- SOURCE CODE FOR JAVATEST.HTML -->

<HEAD>

<TITLE>Example 14.3</TITLE>

</HEAD>

<BODY BGCOLOR="#FFFFFF">

<H1>Growing Text Java Applet Tester</H1>

<FORM METHOD=POST>

Text to display: <INPUT TYPE=text NAME="text" SIZE=40><BR>

Delay between updates: <INPUT TYPE=text NAME="delay"><BR>

Font to use: <INPUT TYPE=text NAME="font" SIZE=40><BR>

<INPUT TYPE=checkbox NAME="bold"> Bold

<INPUT TYPE=checkbox NAME="blur"> Blur<BR>

<INPUT TYPE=button VALUE="Test Applet" onClick="parent['applet'].location='applet.html';"> </FORM>

</BODY>

</HTML>

Input

<!-- SOURCE CODE FOR applet.html -->

<BODY>

<SCRIPT LANGUAGE="JavaScript">

<!-- HIDE FROM OTHER BROWSERS

  document.write('<APPLET CODE="GrowingText.class" WIDTH=500 HEIGHT=200>');

  document.write('<PARAM NAME="text" VALUE="' + parent["form"].document.forms[0].text.value + '">');

document.write('<PARAM NAME="delay" VALUE="' + parent["form"].document.forms[0].delay.value + '">');

document.write('<PARAM NAME="fontName" VALUE="' + parent["form"].document.forms[0].font.value + '">');

document.write('<PARAM NAME="boldBold" VALUE="' + parent["form"].document.forms[0].bold.value + '">');

document.write('<PARAM NAME="blur" VALUE="' + parent["form"].document.forms[0].blur.value + '">');

document.write('</APPLET>');

// STOP HIDING -->

</SCRIPT>

</BODY>

Output

The results appear in Figure 14.3.


Figure 14.3. Using JavaScript, you can reload an applet in another frame with new parameters.

End of Output

Analysis

The process by which you are updating the applet parameters is fairly straight forward.

In the upper frame, you load the form, which you use to change the parameters of the applet. In the lower frame, you load the file applet.html which builds the APPLET and PARAM tags in a script. The script in applet.html assigns the relevant PARAM values based on the values in the form in the other frame (using parent["form"] to reference the named frame).

The file javatest.html makes minimal use of JavaScript. The only place you use JavaScript is in the onClick event handler in the form button where you reload applet.html into the lower frame to get it to restart the applet with the new parameters.

From JavaScript to Java

For many of you, the next step after reading this book will be to look into learning Java. This isn't that outrageous an idea.

By learning JavaScript, you have learned the fundamental syntax used throughout Java. You are familiar with how Java commands are built, how to use loops, and how to build expressions.

Of course, Java is not the same as JavaScript. Besides being compiled and having access to the same set of objects JavaScript does, there are other significant differences:

The result of these and other more subtle differences between Java and JavaScript is that Java programming can be more complex and require more rigorous debugging and organization than JavaScript scripts.

At the same time, with Java it is possible to write complete stand-along applications and perform actions not possible with JavaScript.


The types of applications and applets being developed with Java are wide and varied. A quick glance through a Java archive such as Gamelan shows that the major categories of Java applet development include

Arts and Entertainment: Applets range from portrait painting tools to interactive drag-and-drop poetry creators to simple drawing tools.

Business and Finance: Numerous applets have been created for business applications including stock ticker tapes, real estate viewing tools, shopping carts. and spreadsheets.

Education: The educational applications of Java today include rotateable, three-dimensional molecular models, an interactive abacus, an animated juggling tutorial, and multilingual word matching games.

Multimedia: Multimedia is the most talked-about area of Java development and includes animation tools, fractal drawing applets, electronic publishing systems, audio players, and midi applications.

Network: Applets in this area include terminal emulators and chat applications.

Utilities: Utilities developed as Java applets range from font viewers to graphical calculators to clocks.

JavaScript Into the Future

Currently, JavaScript is limited to products from Netscape. The most prominent use of JavaScript, which we have discussed throughout this book, is the use of the language for developing client-end applications that are integrated into HTML pages displayed in the Navigator 2 browser.

However, Netscape also has implemented JavaScript to use at the server-end, much like CGI programming. Using the Netscape product called LiveWire—a server package for developing sophisticated interactive Web applications—it is possible to create CGI-like scripts using JavaScript. This simplifies Web development in many ways because programming at both ends can be done in the same language, rather than requiring the use of JavaScript for the client end of an application and using Perl, C, or another language for the server end.

At the client end, JavaScript should become increasingly powerful with the release of Navigator 2.1 later this year. Not only will the object hierarchy become richer, adding features such as the applet object, but missing elements such as the Math.random() method will be migrated to all platforms.

At the same time, several plug-in developers have indicated they will provide access to their plug-ins in JavaScript in the form of objects that reflect attributes and functions of the plug-in. This can greatly enhance a JavaScript application by enabling it to work with a range of other file formats, such as Macromedia Director files, Acrobat files, and more.


The following is a list of some of the plug-ins available for Navigator 2.0. Netscape makes a longer list available on the Web at

<A HREF="http://home.netscape.com/comprod/products/navigator/version_2.0/plugins/index.html">http://home.netscape.com/comprod/products/navigator/version_2.0/plugins/index.html

Acrobat Amber Reader (Adobe): A viewer for Portable Document Format (PDF) files—Windows 95/NT

ASAP WebShow (Software Publishing Corporation): A viewer for viewing documents created with SPC's ASAP WordPower presentation software—Windows 95/3.1

Corel Vector Graphics (Corel): A viewer for Corel's CMX vector graphic format—Windows 95/NT

EarthTime (Starfish Software): A plug-in to display the local time in eight geographical locations along with an animated world map displaying daylight and darkness—Windows 95/NT

Envoy (Tumbleweed Software): A viewer for Envoy documents—Windows95/3.1, Macintosh, Power Macintosh

FIGleaf Inline (Carberry Technology): A viewer for multiple graphics formats—including CGM, GIF, JPEG, TIFF, BMP, WMF, and EPS—that includes zooming, panning and scrolling of graphics within Web pages—Windows 95/NT

Formula One/NET (Visual Components): An Internet-capable, Excel-compatible spreadsheet available within Navigator 2.0—Windows 95/NT/3.1

InterCAP Inline (InterCAP Graphics Systems): A plug-in version of InterCAP's MEtaLink RunTIme CGM viewer that supports zooming, panning, and animation—Windows 95/NT

PreVU (InterVU): An MPEG player that supports viewing of MPEG video files while downloading—Windows 95/NT

RealAudio (Progressive Networks): A player for live, on-demand audio files—Windows 95/NT/3.1, Power Macintosh, UNIX (Irix 5.3, Solaris 2.4/2.5, SunOS 4.1.x, Linux 1.2.x or later)

Shockwave for Director (Macromedia): A player for presentations created with Macromedia Director—Windows 95/3.2, Macintosh, Power Macintosh

VR Scout (Chaco Communications): A plug-in to view VRML worlds in Navigator 2.0—Windows 95/NT

Word Viewer (Inso): A viewer for Microsoft Word 6/0 and 7.0 documents—Windows 95/NT/3.1

In addition to these third-party plug-ins, Netscape has introduced Live3D, which promises to add three-dimensional, interactive capabilities to Navigator.

Live3D includes a VRML viewer as well as extending Java and JavaScript. In addition to supporting animation and multimedia (in the form of LiveMedia), Live3D extends the plug-in interface in Navigator to provide plug-ins with access to the 3D space as well as providing Java and JavaScript objects for developing interactive three-dimensional worlds. Live3D is based on the Moving Worlds VRML2.0 specification, which is being considered as a standard.


LiveMedia is Netscape's system for delivering real-time audio and video via Netscape software. Netscape will be making the framework available on the Internet and will be trying to have the technology adopted as an open Internet standard.

Summary

Having learned to use JavaScript, you looked in this chapter at the relationship between JavaScript and Java.

We discussed how the applet object, which will be available in a future version of Navigator, will enable JavaScript applications to interact with Java applets. You also learned how to incorporate existing Java applets into the HTML pages and to use JavaScript to pass custom parameters to the applets you are using.

Finally, you took a look at how to make the move from JavaScript scripting to Java programming and considered the future development of JavaScript.

Q&A

Q: I'm running a PC with Windows 3.1 and lots of memory. When I
try the Java examples in this chapter, they don't work. Why?

A: Java is only supported in the 32-bit Windows version of
Navigator 2.0 (as well as the Mac and UNIX versions). If you
are running Windows 3.1 you are out of luck. There is no known
Java support for Windows 3.1 at this time.

Q: I want to develop an animated logo. Should I use Java or
JavaScript?

A: Although there are examples of simple animations using
JavaScript, JavaScript is not well-suited to the task.
JavaScript animations suffer from speed problems as well as
flickering and inconsistent timing. There are numerous well-
developed, freely available Java applets for animating a
series of GIF images, and these are much better suited for
generating animated logos. Check out the Gamelan archive at
http://www.gamelan.com/ for examples of these applets.

Q: Why can't my Java applets see what is in my HTML forms?

A: This is where Java faces some limitations. It is not able to
see elements of your Web pages such as forms, links, colors,
and so on. This is where JavaScript's role will grow in the
future as it becomes able to pass this type of information to
Java applets.

Previous Page TOC Index Next Page Home