Htaccess    html   Php    javascript   Asp   css    maths  Past Questions  Practice Tests Online

JavaScript to Java Integrating Java into JavaScript tutorial Donate at flattr Flattr this





Alert! Connect with 10,000 Chating Online. Join Now

JavaScript to Java Integrating Java into JavaScript


Learn JavaScript to Java Integrating Java into JavaScript syntax codes and tags using the sample below.

JavaScript to Java Integrating Java into JavaScript syntax




CONTENTS


Now that you've 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 questions remain: How do I do more? Can I move beyond JavaScript and extend its power?

In this chapter, we take a look at the relationship between JavaScript and Java and how you can quickly and easily add Java applets to your pages today. We will also look at how JavaScript can interact with Navigator plug-ins. This intercommunication between Java, JavaScript, and plug-ins is known as LiveConnect, a feature of Navigator 3.0.

In Navigator 2.0, direct communication between Java and JavaScript was not possible. With Navigator 3.0, Netscape has added the applets array, which provides a mechanism for communication between JavaScript and Java.

This chapter first looks at the limited interaction possible in Navigator 2.0, and then introduces the applets array available in Navigator 3.0. We will go on to look at interacting with plug-ins in Navigator 3.0.

You'll learn about the following:

  • Basic Java concepts
  • Using the APPLET tag to use pre-built Java applets
  • Similarities between JavaScript and Java
  • The applets array
  • The plugins array and the plugin object

Integrating Java into JavaScript-The applet Object

When Sun and Netscape announced the creation of 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 middleman and cause information generated by user or browser events outside the applet to be passed to any applet.

Pretty powerful stuff, overall.

The version of JavaScript built into version 2.0 of Netscape Navigator doesn't provide the applet object. Navigator 3.0 supports this feature.

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 interact with Java applets-even in Navigator 2.0.

Basic Java Concepts

Before you can easily use in your Web pages applets that other people have written, you need 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 Developer's Kit is available for SPARC-based hardware running the Solaris operating system and 32-bit Windows platforms (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 Developer's 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 order to understand how to go about obtaining and preparing to use existing applets, you are going to prepare 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 Developer's Kit (which includes the compiler) from Sun's Java home page and have followed the installation instructions. The Developer's 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.

Note
In looking through these archives, you will notice both alpha and beta applets (supported by Navigator). 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.

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


Listing 14.1. The Growing Text applet source code.
/*
 * GrowingText
 *
 * Feel free to re-use any part of this code.
 *
 * Jamie Hall, hallj@frb.gov  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";
  }

}

The demonstration page for this applet looks like Figure 14.1.

Figure 14.1 : The Growing Text applet.

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 with the APPLET Tag

Including a Java 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.

Table 14.1. Attributes of the APPLET tag.

NameDescription
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 Growing Text applet, which you compiled in Listing 14.1, you can now build a simple Web page that displays the applet in a 500¥200-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), several parameters are available for 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.


Listing 14.2. Combining the Growing Text applet into a Web page.
<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>

Figure 14.2 illustrates the effects of the script.

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

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 in Navigator 2.0

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

For instance, with JavaScript's capability 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 Growing Text 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.


Listing 14.3. The parent frameset.
<!-- 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.


Listing 14.4. Source code for the testing form.
<!-- SOURCE CODE FOR JAVATEST.htmL -->

<HEAD>
<TITLE>Example 14.4</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>


Listing 14.5. The code to display the applet.
<!-- 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>

The results appear in Figure 14.3.

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

The process by which you update the applet parameters is fairly straightforward: 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.

The applets Array

Starting with Navigator 3.0, Netscape has added the ability for two-way communication between Java and JavaScript. JavaScript 1.1can call public methods in Java applets as well as work with Java objects and properties, and Java applets can call JavaScript functions.

In this section we will look at how to call Java applets from JavaScript scripts because this is the key tool to making JavaScript the glue for Java applets.

Java applets are reflected into the JavaScipt environment through the applets array-an array of applet objects. Each applet is reflected by a single entry in the array in the order in which it appears in the source code of the HTML document. The applets array is a property of the document object.

For instance, the second applet in a document would be accessed with document.applets[1]. Applets can be named using the NAME attribute of the APPLET tag. The applet

<APPLET CODE="codeURL" WIDTH=width HEIGHT=height NAME=appletName>

could then be accessed with document.appletName.

Properties and methods of the applet are then reflected in JavaScript as properties and methods of the corresponding applet object.

The following listing includes the Growing Text applet used earlier and adds two HTML form buttons-Start and Stop-which allow the user to start and stop the applet:

<HTML>

<HEAD>
<TITLE>applet Example</TITLE>
</HEAD>

<BODY>

<APPLET CODE="GrowingText.class" WIDTH=500 HEIGHT=200 NAME="Growing">
<PARAM NAME="text" VALUE="Java and JavaScript">
</APPLET>

<HR>

<FORM>
<INPUT TYPE=button VALUE="Start" onClick="document.Growing.start()">
<INPUT TYPE=button VALUE="Stop" onClick="document.Growing.stop()">
</FORM>

</BODY>

</HTML>

Here, the onClick event handlers in the INPUT tags are used to call the stop() and start() methods of the Growing Text applet.

The Java Environment

In addition to being able to access properties and methods in an applet, it is possible to access any Java class or package. However, this requires knowledge of the Java environment and how to use Java classes and packages.

More details on how to do this are available on Netscape's Web site. The subject is also covered in detail in the JavaScript Developer's Guide from Sams.net Publishing.

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:

  • Static binding: In JavaScript, you are able to refer to objects in your scripts that may not exist when the script is first loaded and checked for errors. In Java, a program will not compile unless all objects being referred to exist at the time of compilation.
  • Object-orientation: JavaScript implements only a limited object model. Java takes this further to include classes and inheritance-two important aspects of true object-oriented programming.
  • Graphics and GUI capabilities: Java provides graphics primitives and the ability to generate GUI elements that are not available in JavaScript.

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 standalone applications and to perform actions not possible with JavaScript.

None
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 these areas:
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 rotatable, 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.

Currently, JavaScript is limited to products from Netscape, and more recently in the Windows 95 and NT versions of Microsoft's Web browser, Internet Explorer. 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 or Internet Explorer browsers.

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.

Communicating with Plug-Ins

In addition to communication between JavaScript and Java applets, LiveConnect makes it possible for JavaScript to interact with Navigator plug-ins that have been designed to provide LiveConnect support.

Navigator 3.0 includes several plug-ins, such as LiveVideo and LiveAudio, which provide the necessary support for LiveConnect and can be accessed from within JavaScript scripts.

Note
A list of available plug-ins is on the Web
at http://home.netscape.com/comprod/products/navigator/version _2.0/plugins/index.html

The EMBED Tag

Plug-ins are included in an HTML file with the EMBED tag. The EMBED tag is similar to the IMG tag and the APPLET tag. It allows the embedding of a plug-in file format into a Web page to be downloaded when the page is being rendered by the browser.

The tag takes the following attributes:

  • HEIGHT: Specifies the height of the space to allot for the object. HEIGHT is specified in the units defined with the UNITS attribute.
  • SRC: Specifies the URL of the object to be embedded.
  • WIDTH: Specifies the width of the space to allot for the object. WIDTH is specified in the units defined with the UNITS attribute.
  • HIDDEN: Specifies whether the plug-in should be visible. Takes the value true or false and overrides the HEIGHT and WIDTH tags if set to true.
  • PALETTE: Specifies the color palette mode for the plug-in. Can either be set to foreground or background and is only used on Windows versions of Navigator.
  • PLUGINSPAGE: Specifies the URL for a page containing instructions on downloading the plug-in for the embedded type. Used by Navigator's assisted installation feature.
  • TYPE: Specifies the MIME type for the <EMBED> tag. <EMBED> tags require either the SRC or TYPE attribute.
  • NAME: Specifies a name for the embedded plug-in object.
  • UNITS: Specifies the unit of measurement for the HEIGHT and WIDTH attributes. UNITS takes the value pixels or en (which equals half a point size). Pixels is the default value for UNITS.

Similar to frames where the <NOFRAMES> tag provided a mechanism to include alternate HTML code for browsers that don't support frames, the <NOEMBED> tag enables authors to specify HTML code to display in browsers that don't support the <EMBED> tag, and therefore don't support plug-ins.

For example, the HTML code

<BODY>
This is a QuickTime movie:<BR>
<EMBED SRC="sample.qt" WIDTH=100 HEIGHT=100 UNITS=pixels>
<NOEMBED>
<H1>Sorry!</H1>
You need a plug-ins capable browser.
</NOEMBED>
</BODY>

will display the text "Sorry! You need a plug-ins capable browser." in browsers that don't support the <EMBED> tag.

JavaScript includes two objects-mimeTypes and plug-ins-which can be used in scripts to determine if specific plug-ins or MIME types are supported. Both are properties of the navigator object.

The plugins Object

The plugins object is an array of plugin objects, reflecting each of the available plug-ins in the browser.

Each entry in the plugins array has five properties:

  • name: The name of the plug-in.
  • filename: The filename of the plug-in on the local system.
  • description: The description provided by the plug-in.
  • length: The number of plug-ins.
  • mimeTypes: An array indicating the MIME types supported by the plug-in-this has the same characteristics as the mimeTypes object discussed later in this chapter.

You can check for the existence of a particular plug-in by evaluating the plug-in object itself. The code segment

if (navigator.plugins["ShockWave"])
   document.writeln('<EMBED SRC="sample.dir" HEIGHT=50 WIDTH=50>');
else
   document.writeln('Install the Shockwave plug-in');

outputs the appropriate HTML, based on the existence of the Shockwave plug-in.

The mimeTypes Object

mimeTypes is an array of all the MIME types supported by the browser through any means, including plug-ins and helper applications. Each MIME type is represented by a mimeType object. The array itself is indexed by number or by MIME type names.

The mimeType object has three properties:

  • name: The name of the MIME type such as image/jpeg or video/avi.
  • description: A description of the MIME type.
  • suffixes: A string containing a comma-separated list of file suffixes for the MIME type.

For instance, for TIFF images, navigator.mimeTypes["image/tiff"].suffixes might have the value "tiff, tif" and navigator.mimeTypes["images/tiff"].description might be equal to "TIFF Image".

The embeds Array

Whereas the plugins array provides information about each plug-in supported by the browser, the embeds array reflects each of the plug-ins used by an EMBED tag in a document.

The entries in the array reflect each of the EMBED tags in their order of appearance in the HTML source code. The embeds array is a property of the document object. Each entry in the array has no properties or methods, but provides a mechanism for calling the plug-ins methods from JavaScript.

Calling Plug-in Methods from JavaScript

Plug-ins that have been written to interact with JavaScript through LiveConnect make available what are known as native methods. These methods are available to be called by JavaScript scripts as methods of the particular entry in the embeds array.

For instance, most versions of Navigator 3.0 come with the LiveVideo plug-in. This plug-in's object is accessible in Java (and therefore in JavaScript).

The LiveVideo plug-in documentation indicates that it makes four native methods available to the Java environment:

  • play(): Starts playing the source file from the current position.
  • stop(): Stops playing.
  • seek(position): Sets the current position to position where position indicates a frame number.
  • rewind(): Sets the current position to the start of the video.

Using these methods, you can use JavaScript to create a simple control panel for an embedded audio file:

<BODY>

<EMBED SRC="demo.avi" NAME="testVideo" HEIGHT=100 WIDTH=100>

<FORM>
<INPUT TYPE=button VALUE="Play" onClick="document.embeds[0].play(false);">
<INPUT TYPE=button VALUE="Stop" onClick="document.testVideo.stop(false);">
</FORM>

</BODY>

This file uses JavaScript event handlers to provide control buttons for the video file specified in the EMBED tag. Notice that the plug-in is referred to both by its position in the embeds array as well as by name.

Summary

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

We discussed how the applet object allows JavaScript applications to interact with Java applets. You also learned how to incorporate existing Java applets into 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.

A discussion of the mimeTypes and plugins objects, plus the embeds array, provided an introduction to interacting with plug-ins from JavaScript.

Q&A

QI want to develop an animated logo. Should I use Java or JavaScript?
AAlthough 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 more suitable for generating animated logos. Check out the Gamelan archive at http://www.gamelan.com/ for examples of these applets. With the release of Navigator 3.0, which has the images array and the ability to dynamically update images, it is now possible to consider generating JavaScript-based animations.
QWhy can't my Java applets see what is in my HTML forms?
AThis 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 is used to pass this type of information to Java applets.

JavaScript to Java Integrating Java into JavaScript code practice

JavaScript to Java Integrating Java into JavaScript tutorial

JavaScript to Java Integrating Java into JavaScript syntax code on this is provided for your study purpose, it will guide you to know how create and design a website using html. use it to practice and train your self online

All the tutorials on this site are free, the codes are provided for you to practice, if you want to help to improve and maintain this work, you can donate to us on.



Html tutorial guide and web design in easy steps


simple program

Events in

Functions and Objects

introduction to programming

to Java Integrating Java into

Frames Documents and Windows

Data Types in

Loops

strings maths history

insdel

Creating a Spreadsheet in

Language Reference

Building application with 1

Interactive Form object property method

Cookies read cookie set cookie get cookie

The anchor Object [C|2|3|I]

The applet Object [C|3]

The area Object [C|3]

The Array Object [C|3|I]

The button Object [C|2|3|I]

The checkbox Object [c|2|3|I]

The combo Object [C|I]

The Date Object [C|2|3|I]

The document Object [C|2|3|I]

The FileUpload Object [C|3]

The form Object [C|2|3|I]

The frame Object [C|2|3|I]

The Function Object [C|3]

The hidden Object [C|2|3|I]

The history Object [C|2|3|I]

The Image Object [C|3]

The link Object [C|2|3|I]

The location Object [C|2|3|I]

The Math Object [C|2|3|I]

The mimeType Object [C|3]

The navigator Object [C|2|3|I]

The Option Object [C|3]

The password Object [C|2|3|I]

The plugin Object

The radio Object [C|2|3|I]

The reset Object [C|2|3|I]

The select Object [C|2|3]

The String Object [C|2|3|I]

The submit Object [C|2|3|I]

The text Object [C|2|3|I]

The textarea Object [C|2|3|I]

The window Object [C|2|3|I]

Independent Functions, Operators, Variables, and Literals

All the tutorials on this site are provided for free. You can copy and print the tutorials and code on this site, but you are not allowed to reproduce this information on another website. All rights reserverd 2012
 
 
Htaccess    html   Php   javascript   Asp   css    maths  Past Questions