| ## Java 1.1 Unleashed # - 48 - Using Java with VBScript by John J. Kottler IN THIS CHAPTER Wake Up and Smell the Java The VBScript Glue The Infamous Marquee Embedding Marquee on a Page Controlling Java with VBScript Properties versus Methods Triggering VBScript with Java Events The World Wide Web is one of the fastest growing forms of communication today. Not only in the sheer volume of users and computers attached to the Internet, but also in the quality of material found at the countless Web sites. Just over a year ago, typical commercial Web sites featured graphics and text with very little else. Today, however, it is common to find sites that incorporate numerous technologies such as enhanced multimedia, client-side scripting, and Java or ActiveX applications. But just as creating a useful Web site requires more than pretty pictures, creating an interactive Web site requires much more attention to the coordination of events that a user experiences. Throughout this book, you have learned how to assemble the newest technologies available using traditional HTML as well as script languages like JavaScript and VBScript. In this chapter, you learn how to harness the power of Java applets and share data between those applets and the Web browser using the VBScript language. This chapter does not attempt to teach you the Java language or VBScript; instead, it demonstrates how to integrate the two techno-logies. ## Wake Up and Smell the Java No other development language has recently caught the attention of the media and computer industry like Sun Microsystems' Java (`www.javasoft.com`). Java grew from an initiative within Sun to create a development environment for small electronic devices such as pagers and cellular phones. Because of this initial requirement, Java appealed to Web site developers who wanted to create usable applications on their pages. For Internet development, it is necessary that applications do not use a large amount of space because the size of the application directly relates to the amount of time required to download it from the Internet. The Java language is based on the C++ computer programming language, with which many developers are already acquainted. These two reasons alone have greatly contributed to the popularity of Java. Additionally, this robust development language allows developers to create truly unique Windows-style applications that run effortlessly within the confines of an Internet Web browser. Java has become the development language of choice for many Web developers because it offers various advantages for use with the Internet: Java is an object-oriented development environment, which allows developers to create modules for applications that can be shared and reused by other applications. Java produces highly secure executable programs that cannot be altered or misused. Java is a development environment in which a program can be written once, but executed on any type of machine. In a world as diverse as the Internet, each of these features is indispensable. But as appealing as Java is by itself for use on the Internet, it is a development language that is not intended for the faint of heart. The ease of HTML is replaced with a C++ programming language syntax that is foreign to many users. Therefore, it is common to find many sites reusing common Java applets that can be tweaked appropriately for the site, instead of creating entirely new ones. But how is this "tweaking" accomplished and how can these Java applets communicate with more familiar HTML Web pages? ## The VBScript Glue Java applets alone on a Web page cannot communicate directly with each other or with other elements on the Web page. When creating truly interactive Web pages, this communication is essential. Imagine an orchestra in which all the members played their instruments however they wanted. The result would be far from pleasant! However, if everyone followed a musical "script" that coordinated their efforts and communicated to them when to do what, the result would be a beautiful arrangement. The same holds true for Web page development. Although not quite as dramatic as independent musicians in an orchestra, multiple Java applets executing aimlessly on a page add little value to the overall use of the page. But when the applets are directed appropriately using predefined commands like those found in a scripting language embedded within the Web browser, the result is significantly more valuable. In a sense, scripting languages such as VBScript and JavaScript are the glue that hold Web pages and objects on those pages together. In this chapter, you will learn how the VBScript scripting language ties Java applets and Web page material together. With VBScript, you can modify and interrogate the nature of Java applets, which allows you to create pages that extend beyond the traditional capabilities of HTML. You will also learn how it is possible to implement a mechanism with which a Java applet can notify VBScript when a particular event occurs. NOTE: To establish this communication between Java applets and VBScript, it is essential that you understand the basic concepts of object-oriented technology. You may want to review Chapter 3, "Java Language Fundamentals," to brush up on your object-oriented skills. ## The Infamous Marquee In this section, you learn how to use VBScript to control and be controlled by a Java applet. The examples that follow use a `Marquee` applet. Developers who are familiar with the extended HTML tags that Microsoft's Internet Explorer provides will recall the `<MARQUEE>` tag. This tag allows the Web page designer to specify text that scrolls across the Web page. This same effect can be accomplished using the `Marquee` Java applet, which can then be used on any Java- enabled Web browser. Figure 48.1 shows a sample of this applet in use with a blue textual message that scrolls from right to left on top of a white background. Portions of the Java source code for this applet are given in Listing 48.1. A complete copy of the source code for this application is available on the CD-ROM that accompanies this book. FIGURE 48.1. The `Marquee` Java applet scrolls text horizontally within a defined region of the Web page. #### Listing 48.1. The Java source code for the Marquee applet features public variables (properties) and methods for VBScript.
    import java.awt.*;

    public class Marquee extends java.applet.Applet implements Runnable {
    // These are PUBLIC variables, meaning that they can act as
    // properties which can be modified by JavaScript/VBScript
       public String MessageText;
       public int MouseClick=0;

    // If a user clicks within the Java applet, this event will
    // be triggered.
       public boolean mouseDown(Event evnt, int x, int y){
          MouseClick=1;
          return true;
       }

    // When the mouse button is released after being clicked,
    // this event will be triggered.
       public boolean mouseUp(Event evnt, int x, int y){
          MouseClick=0;
          return true;
       }

    // This method will be used by JavaScript/VBScript to update
    // text that appears within the Java applet.
          public void setText(String s) {
          MessageText=s;
       }
       }

    // NOTE:
    // The full source for the init, paint, update and thread control
    // routines can be found on the CD-ROM that accompanies this book.

       }
    }
### Marquee's Properties The `Marquee` applet in Listing 48.1 allows the user to specify numerous settings using `<PARAM>` tags for the applet when embedding the applet on a Web page. However, these tags only specify settings when the applet is first started. You cannot dynamically change settings in the `Marquee` applet using the `<PARAM>` tag. Therefore, the `Marquee` applet also contains two additional properties declared in the Java application as `public` variables. The `public` statement allows other applications or scripting languages such as VBScript to "see" these variables as properties to the Java object. In Listing 48.1, notice that `MouseClick` and `MessageText` are two properties that can be interrogated and set by VBScript. With these two properties available to VBScript, it is possible for a VBScript application to examine what the current message is and change it while the applet is running. The `MouseClick` property can be set or read as well; however, it is dedicated in this case to handling events, as discussed later in this chapter. ### Marquee's Method Because all the functions in the `Marquee` Java applet are `public` functions, they are all technically available for another application such as a Web browser to invoke. However, an additional method specifically for the `Marquee` applet has been provided to set the scrolling text. The `setText()` method instructs the Java applet to change the content of the message being scrolled. Notice that the `setText()` method expects a string as a parameter to the method. This string is the text you pass from VBScript to the Java applet and is the text that should be displayed in the marquee. ### Marquee's Event At the top of Listing 48.1, notice that two events are trapped in the `Marquee` applet: `mouseDown` and `mouseUp`. When a user presses the mouse button down over the `Marquee` applet, the `mouseDown` event is triggered in the Java applet. Likewise, when a user releases the mouse button, the `mouseUp` event is triggered. These events are typical for creating interactive Java applets. In the case of the `Marquee` applet, we are going to use these events to capture when a user clicks on the applet. If a user clicks on the applet, we want to notify a VBScript application on a Web page to take appropriate action. Later in this chapter, you learn how to simulate event trapping in VBScript. ## Embedding Marquee on a Page Now that you have a Java applet that you want to use on a Web page, you must place it on the page. Both Netscape Navigator 2.x and 3.x as well as Microsoft Internet Explorer 3.x support Java applets and their respective tags: `<APPLET>` and `<PARAM>`. You can use these two tags to instruct the browser to insert the Java `Marquee` applet and set its properties accordingly. List- ing 48.2 shows the `Marquee` applet embedded within a simple HTML page. #### Listing 48.2. The <APPLET> and <PARAM> tags are used to embed the Marquee Java applet on a Web page.
    <HTML>
    <TITLE>
    Sample Java Applet
    </TITLE>
    <BODY>
    <APPLET NAME=Marquee CODE="Marquee.class" WIDTH=350 HEIGHT=70>
    <PARAM NAME=BGCOLOR VALUE ="FFFFFF">
    <PARAM NAME=TEXTCOLOR VALUE="FF0000">
    <PARAM NAME=SPEED VALUE="5">
    <PARAM NAME=TEXT VALUE="Enter your text here.">
    </APPLET>
    </BODY>
    </HTML>
NOTE: Each Java applet on a Web page must be uniquely identified by a name (which is specified by the `NAME` property of the `<APPLET>` tag) to be used properly within scripts. Names for applets allow scripts to determine which applets should be affected. The names assigned to applets must consist of standard alphanumeric characters and cannot contain spaces. ## Controlling Java with VBScript So you have a Web page with a Java applet that displays scrolling text. Now what? In some cases, this may be just enough. At times, a Web page developer may want to scroll important messages or advertisements using a marquee and little else. However, there may be times when the marquee's message should change dynamically. For example, a marquee that displays `Good Morning` to a user should display `Good Evening` at night. You can develop a VBScript routine that first determines the time of day and then sets the marquee's message appropriately. ### Invoking Java Methods Let's make the `Marquee` applet interactive to the user. People love seeing their name in lights, so we will create a Web page that accepts text input from an HTML input control and sets the marquee's text to what the user enters. Listing 48.3 shows a simple Web page with the `Marquee` applet, an entry field, and a button that updates the marquee when clicked. Figure 48.2 gives you an idea of what this page looks like. #### Listing 48.3. The Marquee applet can be updated using VBScript.
    <HTML>
    <BODY>
    <APPLET NAME=Marquee CODE="Marquee.class" WIDTH=350 HEIGHT=70>
    <PARAM NAME=BGCOLOR VALUE="FFFFFF">
    <PARAM NAME=TEXTCOLOR VALUE="FF0000">
    <PARAM NAME=SPEED VALUE="5">
    <PARAM NAME=TEXT VALUE="Enter your text here.">
    </APPLET>
    <FORM>
    <INPUT NAME="InputText"
           TYPE=TEXT
           SIZE=35
           VALUE="Enter your text here."
    >
    <INPUT TYPE=BUTTON
           WIDTH=200
           VALUE="Change Text"
          onClick="document.Marquee.setText(form.InputText.value)"
    >
    </FORM>
    </BODY>
FIGURE 48.2. An entry field can be used to type a message to be displayed in the `Marquee` applet. If you are familiar with VBScript or JavaScript, you will quickly realize that calling methods of Java applets is similar to calling VBScript/JavaScript or ActiveX functions. In Listing 48.3, the entry field named `InputText` holds whatever text the user enters. When a user clicks the Change Text button, a single line of VBScript code is invoked. This single line simply calls the `setText()` method of the `Marquee` applet, passing the string from the input field as a parameter for the method. In general, applet methods can be addressed in VBScript using the following notation: `result = document.`Applet Name.Applet Method(Method Parameter) In this syntax, Applet Name is the name you used in the `<APPLET>` tag that uniquely identifies the Java applet on the Web page. Likewise, Applet Method is the name of the method an applet supports that you want to invoke. In addition, some methods may return a value that can be stored in a variable in VBScript, can be tested, or can be used in conjunction with other VBScript functions. According to the source code in Listing 48.1 for the `Marquee` applet, the `void` statement for the `setText()` method indicates that no value is to be returned. If an applet performed some mathematical computation, that method could return the result to VBScript. It is common to invoke a method in a Java applet with some form of data passed to the method. For example, if you were going to use a modem to dial a phone number, you would pass the phone number to the dialing function in the modem. Just as a Java applet does not necessarily return a result value, a method can be designed that does not require input parameters. ### Reading and Writing Properties Just as you can use methods provided by a Java applet in VBScript, you can also alter the properties of an object or determine the properties' current values. To the current `Marquee` example, let's add a second button for a crude guessing game. When a user types a phrase and clicks the Change Text button, the Java applet changes the text in the marquee. When a user then clicks the new Guess Secret Message button, the VBScript code checks the text in the Java applet to see whether it is the secret message. The Guess Secret Message button then posts a message indicating whether or not the user guessed the message correctly. Listing 48.4 presents the new HTML file for this simple game page; #### Listing 48.4. The MessageText property of the Marquee applet can be read by VBScript and tested to create interactive Web pages.
    <HTML>
    <BODY>

    <APPLET NAME=Marquee CODE="Marquee.class" WIDTH=350 HEIGHT=70>
    <PARAM NAME=BGCOLOR VALUE="FFFFFF">
    <PARAM NAME=TEXTCOLOR value="FF0000">
    <PARAM NAME=SPEED value="5">
    <PARAM NAME=TEXT VALUE="Enter your text here.">
    </applet>

    <FORM>
    <INPUT NAME="InputText"
           TYPE=text
           SIZE=35
           VALUE="Enter your text here."
    >
    <INPUT TYPE=button
           WIDTH=200
           VALUE="Change Text"
          onClick="document.Marquee.setText(form.InputText.value)"
    >
    <P>
    <INPUT TYPE=button
          VALUE="Guess Secret Message"
       LANGUAGE="VBScript"
        onclick="if document.Marquee.MessageText='VBScript & Java' then
                      alert(`You guessed the secret message!')
                 else
                    alert(`Nope sorry, try again.')
                 end if"
    >
    </FORM>
    </BODY>
Just like Java methods, properties for applets can be addressed using the following syntax: To read a property's value: `result = document.`Applet Name.Applet Property To set a property: `document.`Applet Name.Applet Property = Value In this syntax, Applet Name indicates the name of the Java applet that was used in the `<APPLET>` tag for the Web page; Applet Property is the name of the variable you want to view or change in the Java application. Properties can be stored in variables in VBScript, used in conditional testing, or combined with other VBScript applications. You can also set properties by assigning values to them. In a sense, properties can be treated as variables in your VBScript applications. FIGURE 48.3. A simple guessing game can be made because VBScript can read the `MessageText` property in the `Marquee` applet. In the computer modem example, the auto-answer capability can be turned on or off. A program can examine the auto-answer property and determine whether it is enabled or disabled. If it is disabled, this property can be changed to a desired setting. NOTE: The names of methods, properties, and respective parameters for various Java applets vary widely. You must consult either the documentation included with the applet or its source code to determine which capabilities are available for the applet. If you are creating your own Java applets, note that functions and variables declared in a Java applet's source code that are to be treated as methods or properties for VBScript must be `public`. If functions or variables are not public, other applications or languages cannot "see" or use them as methods. ## Properties versus Methods As we examined the `Marquee` Java applet along with its properties and methods, you may have asked yourself this common question: "When should I use properties and when should I use methods?" In the `Marquee` example, the results of the `setText()` method could have just as easily been implemented by adjusting the `MessageText` property. If you are creating original Java applets, the decision is up to you when to create methods or properties for use by VBScript. You can base this decision on what makes logical sense. When using commercial or prewritten Java applets or applets without source code, however, you may not have a choice. Each developer will undoubtedly create Java methods and properties to be used by VBScript as logically as possible, although the logic may escape you at times. In general, properties are the characteristics of an object and should be used to change the description of an object. Assume that we have a Java applet that plays video content. Some properties for that object are the filename of the video file to play, the current playback position in the video stream, and the option to display or hide VCR-style control buttons. Methods, on the other hand, are typically used to instruct an object to actually perform an action. Properties typically set static values that in themselves do nothing; methods do the actual work. However, some methods perform differently based on the current properties for an object. Using the video player example again, assume that there are methods for playing and stopping content. We can assume that the playback method plays from the current playback position in the video stream. If the stop and playback methods were invoked immediately after each other, playback would continue from wherever it had stopped last. If, on the other hand, a VBScript program stopped playback, changed the playback position property, and then issued a request to play the stream, the playback method would play from the new position indicated by the position property. ## Triggering VBScript with Java Events So far, you have learned how to control Java applets by invoking methods or changing an applet's properties. The third key component to object-oriented technology has not been addressed: events. In the beginning of this chapter, you saw that the `Marquee` applet traps an event when a user presses the mouse button and traps another when the button is released. The `Marquee` applet was designed so that when a user clicks on the marquee, a specific action can be taken by the VBScript application for a Web page. For this example, the VBScript application will simply post a message indicating that a user has clicked the marquee. VBScript (and JavaScript, for that matter) allows developers to control Java applets through methods and properties, but makes no provision for handling events trapped by a Java applet. Other technologies such as ActiveX provide a mechanism by which, if a particular event occurs in the ActiveX control, corresponding VBScript code can be executed in place of the typical ActiveX code. NOTE: VBScript allows the trapping of events within a VBScript application. Events for ActiveX objects, for example, can be defined and trapped in VBScript by including a subroutine for each event. This subroutine's name must be identified using the ActiveX object name (determined in the `<OBJECT>` tag for the ActiveX control), followed by an underscore (_), and the name of the event to handle in VBScript. For example, the `ActiveMovie` ActiveX control, which is used to display video content and Microsoft NetShow media, contains an `Error` event. As its name implies, this event is triggered whenever an error is encountered. If a VBScript subroutine is created for this event, all error handling can be customized by VBScript rather than using the default actions provided by `ActiveMovie`. The following code shows how to implement this error handling for `ActiveMovie` using VBScript: `sub` MyActiveMovieControl_Error() `` Code to perform when errors occur...` end sub When proper subroutines are established in VBScript for events, actions triggered in an ActiveX control can notify the VBScript application automatically and the results can be handled by custom VBScript code. More information about Microsoft ActiveX and NetShow can be found at the Microsoft Web site: `www.microsoft.com/netshow` Because there is no inherent way to handle Java events in VBScript, we must simulate the process of notifying VBScript when particular events take place in the applet. To do this, we must use the properties of the object that VBScript can access and use a VBScript function that polls these properties on a regular interval. If properties are polled on a consistent basis, we can determine when they change their state in VBScript. If we set aside properties specifically tied to events triggered in the Java applet, the VBScript application can poll for those event properties to change, indicating that an event occurred. ### The Timer Event Because we want to check a Java applet's property on a timed interval, the first step in executing this scenario is to use an ActiveX timer control in VBScript. A timer control can be found at Microsoft's Web site at this URL: `http://activex.microsoft.com/controls/iexplorer/ietimer.ocx` Listing 48.5 displays the tags necessary to embed an ActiveX timer control into an HTML file. #### Listing 48.5. The timer control is an ActiveX control that can be used easily with VBScript.
    <OBJECT
                ID="TimerControl"
            CLASSID="clsid:59CCB4A0-727D-11CF-AC36-00AA00A47DD2"
           CODEBASE="http://activex.microsoft.com/controls/
                     iexplorer/ietimer.ocx#Version=4,70,0,1161"
                TYPE="application/x-oleobject"
             ALIGN=middle
    >
    <PARAM NAME="Interval" VALUE="100">
    <PARAM NAME="Enabled" VALUE="True">
    </OBJECT>
This control expects numerous parameters, but the two of importance are `Interval` and `Enabled`. The `Enabled` parameter is equivalent to a switch that turns the timer control on or off. When set to `true`, the timer is turned on. When the timer is enabled, a `Timer` event is sent to the VBScript for the Web page on a regular interval. This interval is determined by the `Interval` parameter in the `<OBJECT>` tag for the timer control. Time is measured in milliseconds; a value of `1000` is equivalent to a one-second interval. In the sample code shown in Listing 48.5, the interval is set to `100` milliseconds, which is rather quick. The interval is made short because we do not want a user to experience a long delay between clicking the Java applet to trigger an event and seeing the results posted by VBScript. The shorter this delay is, the quicker the response. NOTE: The `Interval` property of the `Timer` ActiveX control can be adjusted to trigger the `Timer` event after any given amount of time. Longer delays are suitable for other types of applications that may use timers (such as a clock that updates every second or minute). But a shorter duration is required to emulate the immediate triggering of VBScript code by a Java applet. When the parameters are set appropriately for the timer control, the timer triggers an event in VBScript every given number of milliseconds. In this example, the VBScript event `TimerControl_Timer` is executed every 100 milliseconds. The code in the `TimerControl_Timer` function can then read a Java applet's property and determine when it has changed. List- ing 48.6 shows a sample of appropriate VBScript code for detecting changes in the `Marquee` applet's `MouseClick` property. #### Listing 48.6. Once a timer control is enabled on a Web page, VBScript can check Java properties on a regular basis to determine when they change.
    <SCRIPT LANGUAGE="VBScript">
    sub TimerControl_Timer()
        if document.Marquee.MouseClick=1 then
           document.Marquee.MouseClick=0
           alert("You clicked on the Java applet!")
        end if
    End Sub
    </SCRIPT>
> In this case, the `mouseDown` event in the `Marquee` applet's source code assigns the public variable `MouseClick` the value of `1`. Likewise, the `mouseUp` event resets this property to `0`. Because these properties are available for interrogation in VBScript and are tied closely to the events in the applet, they can be used to notify VBScript when the event has occurred. TIP: As shown in Listing 48.6, it is recommended that you reset the properties for an event where appropriate. Although the Java applet should reset the property automatically, there may be occasions when it will not. Resetting the properties when you are finished using them is good practice to avoid these events from triggering more than the number of times expected. For example, in Listing 48.6, if the `mouseClick` property was not reset, a new alert box would appear every 100 milliseconds! NOTE: Although we have discussed how to implement a timer in VBScript using only ActiveX controls, you can also implement this same technique using JavaScript. Instead of using a timer control, JavaScript uses the `setTimeOut()` function available in the language. This function instructs JavaScript to execute a particular function on a regular interval. By placing the `setTimeOut()` function within the function to be called regularly, a looping condition can occur, in which the function is called continuously on a given interval. The only exception to note in this implementation is the use of the `<BODY>` tag, which uses the `onLoad` event to initiate the entire timer process. The following code shows how to implement a timer in JavaScript:
>     <BODY onLoad="tf=setTimeOut(`TimerFunc()',100)">
>     ...
>     </BODY>
>     <SCRIPT LANGUAGE="JavaScript">
>     function TimerFunc(){ tf=window.setTimeout("TimerFunc()",100);

>         if (document.Marquee.MouseClick==1){
>             document.Marquee.MouseClick=0;
>             alert("You clicked on the Java applet!");
>         }
>       }
>     </SCRIPT>
### On the Java Side As you can see, it is possible to trigger VBScript functions when an event occurs in a Java applet on a Web page. However, for this to work correctly, there must be appropriate properties available for VBScript to use. In the `Marquee` applet, a special `MouseClick` property was designed explicitly for this purpose. When a user clicks the mouse button over the Java applet, the applet's `mouseDown` event is triggered, setting the `MouseClick` property to `1`. The VBScript code for the Web page can then interrogate the `MouseClick` property to "see" when it changes from `0` to `1` and act accordingly. Likewise, the `mouseUp` event for the `Marquee` applet resets the `MouseClick` property to `0` so that a user can click the applet and trigger the VBScript code again in the future. The `MouseClick` property was specifically designed for use with VBScript to indicate when the mouse button is down or up. When designing your own Java applets or modifying applets for which you have the source code, it is easy to add dedicated properties for events to be captured by VBScript. When reusing Java applets that you cannot modify, it becomes increasingly difficult to implement similar event trapping techniques in VBScript--mainly because you cannot add your own custom properties to interrogate with VBScript. If you use Java applets for which you do not have the source, you may still be able to trap events with VBScript. To do so, however, you must think of other properties that the applet does support that may indicate when particular events occurred. Consider the fictitious video player applet discussed earlier. Assume that we do not have the source code for this applet and want to create a routine in VBScript that performs a specific action when the playback stops. If the applet supports a `CurrentPosition` property, we can still implement a "stop" event in VBScript. If this `CurrentPosition` property updates continuously to indicate the position in the video file at which playback is located, it is possible to simply watch this property with a VBScript timer subroutine to determine when the position does not move anymore. This is essentially the same as indicating that the playback of the video stream has stopped. ## Summary In this chapter, you learned how to interface Java applets with VBScript. You saw how to change properties of Java applets and invoke methods that applets support. You also learned how to simulate event trapping in VBScript and JavaScript. With this knowledge, you can implement more complex Web pages that effectively communicate with Java applets to create unique applications. In Chapter 49, "Developing Intranet Applications with Java," you learn how to leverage Java technology to increase the functionality of an organization's intranet.
| ©Copyright, Macmillan Computer Publishing. All rights reserved.