Lean CSS
Welcome to CSS
Introduction to CSS
CSS Syntax
Insert style sheet
CSS Background
CSS Text
CSS Font
CSS Border
CSS Margin
CSS Padding
CSS List
CSS Dimensions
CSS Classification
CSS Positioning
CSS classes
CSS elements
CSS2 Media Types
CSS Units
CSS Colors
 

Free Tutorials
HTML
Learn HTML
Learn CSS
Learn XML
Learn WML
Database
Learn Access
Learn Data-VB
Learn Oracle
Learn SQL
Programming
Learn C++
Learn JavaScript
Learn Vbscript
Learn VisualBasic

Chapter 16

Integrating JavaScript with Java


CONTENTS

As I mentioned in Chapter 1 there's not much relation between Java and JavaScript-except for the name. However, they can both be useful on your Web pages-sometimes at the same time. This chapter begins with an introduction to the Java language and its capabilities.

JavaScript also includes functions to control Java applets, and Java applets can access JavaScript functions. By integrating these two Web languages, you can have the best of both worlds, allowing for many complicated applications.

An Overview of Java

Let's begin with a tour of the Java language, the development process for Java applets, and the way Java and HTML interact. If you're unfamiliar with Java, this will give you a quick start and help you understand how Java and JavaScript can work together.

Note
Java is a complex language-much more so than JavaScript. This chapter introduces Java, but can't explain it in detail. If you want to learn more about Java, consult the online resources listed in appendix C, or pick up a copy of the bestselling Teach Yourself Java in 21 Days, by Laura Lemay, also from Sams.net publishing.

How Java Works

Some languages, such as C, are compiled into executable programs before they can be run. Others, such as JavaScript, are interpreted directly from the source code. Java is something in between.

A Java program starts out as source code and is then run through the Java compiler. The compiler doesn't produce true machine code, though-instead, it produces code for a virtual machine. This virtual machine code can then be interpreted by an implementation of the virtual machine, such as Netscape.

Note
To complicate things even more, the latest versions of Netscape and MSIE include Java compilers. Called just-in-time compilers, these compile Java virtual machine code into executable code before running the applet. This greatly increases the speed of applets.

There are actually two types of Java programs:

  • A Java application is a complete program, such as a Web browser.
  • A Java applet is a program that is meant to run within a Web browser. All Java programs you can run from the Web are applets. The next sections focus on applets.

The Java Language

The Java language is similar to C++. You may also notice a similarity to JavaScript; Netscape loosely based the JavaScript syntax on that of Java.

Like JavaScript, Java includes statements and functions. It also includes objects, properties, and methods. You will look at a simple example of a Java applet in the section titled Creating Your Own Java Applets later in this chapter.

Java Objects and Classes

Java is an object-oriented language-much more so than JavaScript. A Java applet is actually a class; running an applet means creating an instance of the class. Technically, applets are subclasses of the Applet object.

There are also several object classes you can import into a Java program. These provide functions such as graphics, fonts, working with strings, and so on. You'll look at a class later that enables Java to access JavaScript objects.

Integrating Java with HTML

Unlike JavaScript, Java code is never included in the HTML file itself. Instead, a special HTML tag, <APPLET>, is used to embed the applet in the Web page. Here is a simple example of an applet:

<applet code="Applet1.class" width=55 height=68> </applet>.

Notice that both opening and closing <APPLET> tags are required. Between them, you can use optional <PARAM> tags to give parameters to the applet. The parameters required depend on the applet. Each <PARAM> tag includes a variable name and value:

<PARAM name=height value=100>

Tip
You can also use JavaScript to choose between a Java or non-Java version of a page. Use the Navigator.javaEnabled property, described in Chapter 4 "Using Built-In Objects and Custom Objects."

The next section presents a complete HTML file with an embedded applet. For examples of embedding public domain Java applets into your pages, see Chapter 19, "Real-Life Examples IV."

Note
Currently, most complicated Java applets are a bit slow. If you include one in your Web page, be sure you test it carefully; you may also wish to warn users that an applet is loading.

Creating Your Own Java Applets

To create your own Java applets, you use the Java Development Kit (JDK). This includes the Java compiler, example applets, and an applet viewer. The JDK is available at no charge from Sun.

Tip
The JDK is also included on the CD-ROM that accompanies this guide, along with a variety of sample applets.

The JDK is available for the following platforms:

  • Windows 95
  • Windows NT
  • UNIX (SPARC or x86 Solaris only)
  • Macintosh (Power Mac only)

Note
Currently, there is no version of the JDK for Windows 3.1 or 68000-series Macintosh. You will need to use a different platform to compile Java applets, although you can still view applets in Netscape. If you have a shell account with your Internet provider, you may be able to use the JDK from there.

The following tasks explain how to download and install the JDK, use it to create a simple Java applet, and compile and view the new applet.

Installing the Java Development Kit

To download the JDK, visit Sun's Java Web page at the following address:

http://java.sun.com/

and follow the appropriate links. At this writing, the latest version of the JDK is 1.02. Once you've downloaded it, the installation process depends on your platform:

  • For Windows 95 or NT, start a DOS session. Copy the self-extracting archive file to the directory or drive you wish to install the JDK in, and execute it. It will be unpacked into a java directory with several subdirectories. The JDK needs about 5M of space to unpack.
  • For Solaris, the JDK comes in a compressed tar file. You can expand it into the directory of your choice with this command:
    /usr/bin/zcat JDK-1_0_2-solaris2-sparc.tar.Z | tar xf -
  • For Macintosh, the JDK is available in MacBinary or hqx format. Expand the file with a utility such as StuffIt, DeHQX, or BinHex4. Run the installer program, which will create a folder on your desktop for the JDK.

Creating a Simple Java Applet

Now let's try creating a simple Java applet. Listing 16.1 shows a Java applet that displays a message in a large font.


Listing 16.1. (JavaTest.java) A simple Java applet that displays a message.
import java.applet.Applet; import java.awt.Graphics; import java.awt.Font; public class JavaTest extends Applet { Font f = new Font("TimesRoman", Font.BOLD, 60); public void paint(Graphics g) { g.setFont(f); g.drawString("Text from Java", 15, 50); } }

Here is a brief explanation of the program. The first three lines are Java import statements. These specify three classes (libraries) used by the applet:

  • java.applet.Applet is a standard class that must be imported for any applet.
  • java.awt.Graphics is part of the awt API, which handles the GUI for Java. This library includes functions for graphics.
  • java.awt.Font includes functions to handle text with fonts.

Next, the class definition begins with the public class JavaTest statement. You're defining a class called JavaTest, which is a subclass of the Applet class (as all applets are).

The next statement, Font f = new Font, defines an instance of the Font object, an object used to store information about a font and size. The new Font object is called f. (Notice the similarity to the new keyword for defining objects in JavaScript.)

The next statement begins the paint function, which is the main program. This also defines a new Graphics object called g. The next two statements are methods of the Graphics object; methods in Java work much like JavaScript.

The g.setFont() method sets the font to be used when drawing text, and the g.drawString() method draws the text on the screen in the applet's area.

Compiling and Viewing a Java Applet

Now that you have a simple Java applet, you need to compile it and use it in an HTML page. Be sure you have placed the applet source code in a file called JavaTest.java.

First, compiling the applet is simple. Type the following command from the directory where you installed the JDK:

bin\javac JavaTest.java

The compilation process should take only a few seconds. If no errors were found, the compiler won't display any messages. After the compilation, you should have a file in the same directory called JavaTest.class. This is the Java class file that you can use on a Web page.

Note
Just about everything in Java is case-sensitive-source files, class files, and the <APPLET> tag. Be sure you use the exact names.

To test the new applet, you need to embed it in an HTML page. Listing 16.2 shows a simple HTML page that includes the applet created previously. Create this HTML file in the same directory as the class file or copy the class file into its directory.


Listing 16.2. (JAVA1.asp) An HTML file to test the new Java applet.
<HTML> <HEAD> <TITLE>Simple Java Test</TITLE> </HEAD> <BODY> <h1>test</h1> <hr> An applet is included below to display some text. <hr> <APPLET CODE="JavaTest.class" WIDTH=450 HEIGHT=125> </APPLET> <hr> applet finished... here's the rest of the page. </BODY> </HTML>

The <APPLET> tag in this file includes the filename of the JavaTest class and a width and height. Be sure to include the closing </APPLET> tag, although there may be nothing between the two tags.

Now that you have an HTML file, you need to test it. A simple way to do this is with the applet viewer, included with the JDK. You can start the applet viewer by typing the following command in the JDK directory:

bin\appletviewer file:\Java\JavaTest.asp

Tip
You may need to modify this command to work on your system. You can also add the java\bin directory to your path to avoid typing bin\ before each command.

Although you started the applet viewer from a command line, the actual output is shown in a graphical window. Figure 16.2 shows the applet viewer in action, using the example applet.

Figure 16.1 : The Java applet viewer in action.

Notice that the applet viewer shows the output of the Java applet, but does not include the text from the HTML file itself. This may be useful when you're debugging a Java applet. To see the entire HTML file including the applet, you'll need to use a browser, such as Netscape.

To test the applet in Netscape, simply use the Open command to load the HTML file created previously. Figure 16.2 shows the applet example as viewed by Netscape.

Figure 16.2 : The Java applet in action, as viewed by Netscape.

Note
Once you've created and debugged a Java applet, you'll probably want to publish it on the Web. To do this, simply place the class file for the applet in the same directory as the HTML file on the Web server.

Using Java Classes with JavaScript

In Navigator 3.0b4 Netscape introduced a new feature called LiveConnect, which provides the following capabilities:

  • JavaScript programs can communicate with and control Java applets.
  • Java applets can access JavaScript objects, properties, and methods.
  • JavaScript programs can control Netscape plug-ins.

You will look at the first capability in this section: accessing Java classes (applets) from within JavaScript. You will look at the opposite method in the section titled Calling JavaScript functions from Java, later in this chapter.

Calling Java Methods

You can call Java methods directly from JavaScript. This means you can treat methods as if they are JavaScript statements themselves. For example, this statement prints a message to the Java console:

java.lang.System.err.println("This is a test.");

This will be most useful if you are an experienced Java programmer. If you are not, you can use JavaScript to take advantage of features of existing Java applets, as described in the next section.

The applet Object

Each Java applet you embed in a Web page is made available to JavaScript as an applet object, with the same name as the applet's class name. The applet object resides in the object hierarchy under the document object. For example, a Java applet called Scroll would be accessed through an object called document.Scroll.

The objects, properties, and methods of the applet are then available to JavaScript, provided the Java programmer has made them public. You will use this technique to control a Java applet in the task later in this section.

Note
There is an exception to the rule: any Java method that communicates over the network can't be called from JavaScript. This limitation exists for security reasons.

Making the Java Applet Accessible

From the Java programmer's point of view, there are a few things that need to be done to make an applet accessible to JavaScript:

  • Define the methods you want to make accessible as public methods.
  • Be sure the Netscape package is included in your CLASSPATH environment variable when the applet is compiled.

Once you've made sure of these things, you should be able to access the applet from within JavaScript. The next section gives an example of an applet that is controllable by JavaScript.

Controlling a Java Applet

Let's create a Java applet that can be manipulated from within JavaScript. Listing 16.3 shows the Java source code. This is an expanded version of the example in Listing 16.1.


Listing 16.3. (ControlJava.java)A Java applet that can be controlled via JavaScript.
import java.applet.Applet; import java.awt.Graphics; import java.awt.Font; public class ControlJava extends Applet { Font f = new Font("TimesRoman", Font.BOLD, 60); String Message; public void init() { Message = new String("Java Test"); } public void SetMessage(String MsgText) { Message = MsgText; repaint(); } public void paint(Graphics g) { g.setFont(f); g.drawString(Message, 15, 50); } }

This applet now includes a SetMessage() method to change the text in the display. Listing 16.4 shows the HTML and JavaScript document used to control the applet.


Listing 16.4. (CJAVA.asp) The JavaScript program to control the Java applet.
<HTML> <HEAD> <TITLE>Control a Java Applet</TITLE> </HEAD> <BODY> <H1>Control a Java Applet</H1> <HR> The Java applet below displays text in a large font. You can enter new text to display in the form below, and JavaScript will call the Java applet to change the text. <HR> <FORM NAME="form1"> <INPUT TYPE="TEXT" NAME="text1"> <INPUT TYPE="BUTTON" VALUE="Change Text" onClick="document.ControlJava.SetMessage(document.form1.text1.value);"> </FORM> <HR> <APPLET NAME="ControlJava" CODE="ControlJava.class" WIDTH=450 HEIGHT=125> </APPLET> <HR> End of page. </BODY> </HTML>

This uses a simple event handler to call the Java applet's SetMessage() method. The string you enter in the text field is passed to the applet and displayed in place of the original string. Figure 16.3 shows this application in action after the text has been changed.

Figure 16.3 : JavaScript has changed the text by accessing the Java applet.

Calling JavaScript Functions from Java

It's also possible to call JavaScript functions, and access JavaScript objects and properties, from within Java. This enables you to use JavaScript's unique capabilities, such as reading the values of form elements, in powerful Java applications.

To make JavaScript functions accessible from Java, you need to configure things both in JavaScript and in Java. You'll look at the required steps in the next sections.

Steps for the JavaScript Programmer

It's possible for a Java applet to do things you don't want it to, so you must give permission for it to access your JavaScript program and objects. To do this, add the MAYSCRIPT attribute to the <APPLET> tag that embeds the applet:

<APPLET CODE="Script.class" NAME="TestApp" MAYSCRIPT> </APPLET>

Steps for the Java Programmer

For the Java programmer, there are also some important steps before you can access JavaScript. First, you need to include the netscape.javascript package, which provides these functions, in your imported classes:

import netscape.javascript.*

Next, you need to create a handle for the JavaScript window. To do this, define a variable of type JSObject and use the getWindow method to assign it:

JSObject js = new JSObject; js = JSObject.getWindow(this);

Accessing JavaScript Objects

Once you have a handle for the JavaScript window, you can get the objects you need to access. To do this, you need to call the getMember method for each property. For example, to make the text1 field on the form1 form accessible:

js = JSObject.getWindow(this); JSObject document = (JSObject) js.getMember("document"); JSObject form1 = (JSObject) document.getMember("form1"); JSObject text1 = (JSObject) form1.getMember("text1");

You are creating an object of type JSObject for the document, then for each object underneath it.

Calling JavaScript Functions

You can also call JavaScript functions and methods from within Java, using the same technique. The two methods you use for this purpose are call and eval. For example, this statement calls a JavaScript method to display an alert message:

js = JSObject.getWindow(this); js.call("window.alert('This is a test.');");

Workshop Wrap-Up

In this chapter you learned about Java and how it can work with JavaScript:

  • The basics of how the Java language and compiler work
  • Where to get the Java Development Kit (JDK) and how to install it
  • How to create and compile a simple Java applet
  • How to embed a Java applet in an HTML page
  • How to use JavaScript and LiveConnect to control a Java applet
  • Using JavaScript objects, functions, and methods from within a Java applet

Next Steps

You can continue exploring JavaScript and Java with one of the following chapters:

  • To learn how to combine JavaScript with other popular Web languages-CGI and SSI-turn to Chapter 17, "Combining JavaScript, CGI, and SSI."
  • To learn about Microsoft Internet Explorer, ActiveX, and VBScript, turn to Chapter 18, "Using ActiveX and Microsoft Internet Explorer."
  • To see examples of using Java applets and controlling them via JavaScript, see Chapter 19, "Real-Life Examples IV."
  • To learn about the future of JavaScript, Java, and other Web languages, turn to Chapter 20, "The Future of JavaScript."

Q&A

Q:
Can I access third-party Java applets from JavaScript, particularly those that were created without JavaScript in mind?
A:
Usually not. The applet must include the Netscape package, which includes the required functions for JavaScript and Java communication.
Q:
Can I use more than one Java applet in a Web page?
A:
Yes. However, note that this may cause severe slowdowns (and sometimes crashes) in some versions of Netscape.
Q:
Judging by the examples in this chapter, Java isn't very similar to JavaScript. Why on earth do they have similar names?
A:
JavaScript was originally called LiveScript, but was renamed after Java. Although some of the syntax is based on Java, it's a very different language.






|  About us | Categories | New Releases | Most Popular | Web Tutorial | Free Download | Drivers |



2013 Softlookup Corp. Privacy Statement