Previous Page TOC Next Page See Page



- 14 -
Introducing Java


For all its capabilities, JavaScript is still very much bound by the existing features of your Web browser. As the name in fact suggests, JavaScript is designed not as a programming language, but as a scripting language that enables you to control elements on your Web pages.

If you are looking for a means to add new functionality to the World Wide Web, you need to turn to Java itself. In this chapter, you will learn about Java by examining the following topics:


What Is Java All About?


Java was originally developed by a small advanced projects team at Sun Microsystems, as part of a somewhat misdirected attempt to move into the mainstream consumer market. In its early days, Java—originally named OAK, reputedly after the tree outside its creator James Gosling's office window—was designed as the programming language for an interactive controller called a Portable Data Assistant (PDA).

What made this device unique was the fact that the technology it encompassed could be embedded into nearly any type of electronic consumer product. By doing so—due to its built-in graphical user interface and of course OAK—the device could be programmed to perform any operation desired. For example, if used with a VCR, it could replace all the buttons and dials with a easy-to-use graphical display and touch screen that guided people through the steps required to set the time and program their favorite shows. At the lofty heights envisaged by the special projects team, there was no consumer product that could not benefit in some way from the PDA. It has been rumored that there was even a suggestion at one stage that an electric toaster with an infrared receiver could be programmed to deliver the perfect golden-brown piece of toast.

Unfortunately, this wonderful device somehow got lost in the hype surrounding the information superhighway. In its place, the special projects team, which by this stage was known as FirstPerson Inc., set its sights on the interactive set-top television market and the plans of companies such as TimeWarner, who were considering such devices as a means of delivering Video on Demand and other interactive services through cable.

After many months of negotiations, the team was unable to close any deals with even one potential customer, and as a result, the future of FirstPerson and all the devices it had developed hung in the balance. Eventually all of these projects were abandoned, but there was one resource whose potential had not been fully explored. This resource was the OAK language that had been at the heart of all the devices created by FirstPerson.

Programming the World Wide Web


By the time the activities of FirstPerson were being wound up, the Internet, and more specifically the World Wide Web, was rapidly becoming part of everyday life for companies such as Sun. It was at this time that Bill Joy—one of Sun's cofounders—realized that OAK was an ideal language for the Internet and the World Wide Web.

As a result, after some prodding, James Gosling and Patrick Naughton, who was the catalyst for the original FirstPerson project, began to form OAK into the ultimate Internet development environment. Then, as if to signal the final death of FirstPerson, OAK was renamed to Java, and the language found in Navigator 2.0 and 3.0 was born.

The Java Language


But enough history. What exactly is Java, and why would you want to use it?

At its heart, Java is an object-orientated programming language similar to C++. Unlike C++, however, Java was designed with portability capability. In the Internet world, there are various computer platforms, all of which use different operating systems and require programs written in languages like C++ to be specially crafted to suit their individual needs. As a result, you cannot simply take a C++ program written for a Macintosh computer and run it on your Windows 95-based PC.

Java, on the other hand, was designed so that you can do just that—write a program once and have it run on many different computer platforms. To achieve this goal, Java programs are compiled into what is called an architecture-neutral byte-code. What this basically means is that the programs are platform nonspecific. When in this architecture-neutral form, Java programs can be run on any computer platform that supports what is called a Java runtime.

Currently, Java runtime modules are available for Windows 95, Windows NT, Apple Macintosh, and a small number of UNIX-based X-windows systems, including HP-UX, SGI IRIX, SunOS 4.1, and Sun Solaris 2.3 or 2.4.

Distributed Programming


The second major feature of Java is the one that makes it such a viable tool for use with the World Wide Web. To use the technical definition, Java is a distributed language.

What this really means is that through the Internet, Java programs can be transferred from computer system to computer system without any intervention by the user or, because of its application-neutral technology, any concern about the type of computer system to which it is being sent.

When this capability is incorporated into a Web browser such as Navigator 3.0, the true power of Java becomes apparent. Take, for example, the GolfWeb home page shown in Figure 14.1. The small window in the Middle of this page contains a window a lot like a ticker-tape display. In this window, headlines for all the latest breaking Golf news are scrolled across the window from right to left.

Figure 14.1. GolfWeb uses Java to create its online ticker tape displays.

You might have noticed that there has been no mention throughout this book of such a feature in HTML. That's because currently there is no such capability. So how does c|net make this magic work? Or more importantly, how do you make it work on your Web browser?



Note:

The Microsoft Web browser Internet Explorer does include an extension to the HTML that adds an element called <MARQUEE>. This element creates a scrolling area on a Web page, but it lacks many of the features available when you code such a window in Java.


To add the ticker tape display to their Web pages, the developers at c|net wrote a small Java program. This program draws the ticker tape window on the Web page and looks after scrolling the messages.

Writing such a program is not a difficult task. What places Java in a world all its own is that when a Java program (or applet) is included as part of a Web page, the applet is automatically transferred and installed on the computer in question, without any user intervention.

What Can Java Be Used For?


Basically, there is very little limitation to the possible applications for Java applets and Java-based applications. To this extent, Sun has even created a Web browser called HotJava that was written entirely using the Java language.



Note:

Java programs generally fall into one of two specific categories: Java applets, which are designed to be embedded inside a Web page, and Java applications, which are stand-alone Java programs. These programs are fully self-contained and don't run within a Web browser at all.


In fact, about the only real limitation imposed by Java is in the imaginations of Web developers. And if the crop of Java applets that have sprung up since the launch of Navigator 3.0 is any indication, some very imaginative minds are at play on the World Wide Web.

Blue Skies Weather Underground

Take for example the Blue Skies Weather Underground, operated by the University of Michigan. (See Figure 14.2.) This site represents one of the best current examples of the incredible interactive capabilities that Java brings to the World Wide Web. The Weather maps and the various gadgets surrounding it in Figure 14.2 are all part of a single Java applet, which enables you to view the current weather report for major cities by highlighting them with the cursor. In addition, by clicking various regions of the map, you can zoom in for a close-up look at individual weather patterns, or, alternatively, view a movie of the weather pattern for the past 24 hours.

Figure 14.2. View the latest weather maps for the mainland US by using Java and Blue Skies.

What makes this service so amazing is that it all happens within one easy-to-use screen. Without Java, you would probably need many hundreds of separate Web pages to create a similar service, and even with all these pages, you would still not be able to easily duplicate some features, including the line-drawn U.S. maps over the satellite images that are created on the fly by Java itself.

To experiment with the features offered by the Blue Skies service, point your Web browser to http://cirrus.sprl.umich.edu/javaweather/.

Gamelan

To give yourself an even better idea of the possibilities offered by Java, point your Web browser to http://www.gamelan.com/, as shown in Figure 14.3. This site contains the most up-to-date directory of sites using Java. It also includes a large collection of applets that demonstrate the wide variety of reasons why people are starting to incorporate Java into their Web pages—reasons such as these:

Figure 14.3. Gamelan is regarded as the repository for Java applets.

Netscape and Sun

Apart from Gamelan, both Netscape and Sun also operate their own directories of Java applets along with a wide variety of related information. To visit the Netscape directory shown in Figure 14.4, use http://home.netscape.com/comprod/products/navigator/version_2.0/java_applets/index.html. This index contains pointers to all the latest Netscape-related Java information, along with some of the more popular Java applets.

Figure 14.4. Netscape is another good source of information about Java and its capabilities.

To provide even more information about Java, Sun has set up an entire Web site devoted just to the subject, as shown in Figure 14.5. This site contains up-to-the-minute details covering all aspects of Java development and usage, and it is also the primary source for Java development tools and documentation.

Figure 14.5. http://java.sun.com/ is the home of Java.

http://java.sun.com/

Programming with Java


Due to the size and complexity of the issues involved in using a programming language like Java to its fullest advantage, dealing with all the intricacies of Java programming is beyond the scope of this book. Therefore, instead of dealing with the actual programming techniques involved, in this section you will work through the creation of a simple ticker tape display like the one shown previously in Figure 14.1. In this way, you'll get a better idea of what Java is all about.

For those of you who are keen to learn more about the internals of Java, a copy of the complete Java documentation written by Sun Microsystems has been included on the CD-ROM accompanying this book. To view this documentation you will first need to install a copy of the Adobe Acrobat reader—also available on the CD-ROM on both Macintosh and Windows versions.



Note: For a full discussion of Java programming, refer to "Presenting Java" and "Teach Yourself Java in 21 Days," of "Java Unleashed," also by Sams.net.


The Java Developers Kit (JDK)


Before you begin creating your own Java applets, you must get a copy of the current version of the Java Developers Kit, known currently as the Java 1.1 JDK. This kit contains all the tools required to compile Java applets, the most up-to-date libraries (called classes), a stand-alone applet viewer to test your applets without the need for Navigator 3.0, and a debugging utility to help locate problems in your Java code.



Note:

In object-oriented terms, the class is the basic structural framework for all program design. A class is a bit like a library of pre-built instructions, or a template that you can enhance to create new classes and entire applications. Although it is not vitally important that you understand all the concepts surrounding object-orientated design and development as you start to use Java, you might find it very handy to get a good book on the subject.

One such book is Object-Orientated Analysis and Design with Applications, by Grady Booch, Published by Benjamin/Cummings Publishing Company. Alternatively, you might check out An Introduction to Object-Oriented Programming, by Timothy Budd, Published by Addison-Wesley Publishing Company. Or you can read Object-Oriented Technology: A Manager's Guide, by David A. Taylor, Ph.D., published by Servio Corporation.


To get a copy of the JDK for your particular computer system, point your Web browser to http://java.sun.com/java.sun.com/products/JDK/index.html, as shown in Figure 14.6. Sun currently provides JDKs for Windows 95, Windows NT, Mac OS and SPARC/Solaris 2.3, 2.4, or 2.5 systems. JDKs for other systems are expected in the near future.

Figure 14.6. To create Java applets, you must install a copy of the Java Development Kit on your computer.



Note:

An alternative method for compiling Java applets is provided by the Black Star Public Java Compiler—http://mars.blackstar.com/. This site operates a Web page where you can submit Java programs for compilation. For any serious use, however, you really do need to install the JDK on your local computer.



Exercise: Creating a Ticker Tape Applet

After you have downloaded the appropriate JDK, you need to unpack the archive file as described on the JDK Web pages or in the documentation included with the JDK archive. Then you should be ready to start building your first Java applet.

You can write Java programs by using a simple text editor, or alternatively, you might want to use a program editor of some sort. It really does not matter what you use, because Java source code is plain text.

Under Windows 95, however, I currently use a program called PFE (shown in Figure 14.7), which can be obtained from http:://www.lancs.ac.uk/people/cpaap/pfe/. The one advantage of using a program like this, over using a normal text editor, is that you can perform actions such as compiling your code from inside the editor itself instead of having to start a separate MS-DOS shell.

Figure 14.7. Program editors can control repetitive tasks such as compiling your Java code.

Finally, in recent months a number of companies have begun to release what are know as Integrated Development Environments (IDEs) specifically for Java programming. (See Figure 14.8) These environments incorporate an editor and other tools like class browsers and a Java compiler into a single application. For more information on such systems take a look at the Gamelan Web site mentioned previously.

Figure 14.8. Café by Symantec.

After choosing your editor, create a new directory to hold your Java applets. Start the editor and create a new file called Ticker.java. (Be sure to include the capital T because Java is very case specific.)

Java Framework

At its heart, Java is an object-orientated language. As a result, when you are working with Java applets, you are really adding functionality to the basic applet framework defined in the JDK. For this reason, the basic structure of all Java applets looks almost identical.

The basic framework for the Ticker Tape applet looks like the following:

/* Exercise - Ticker.class */
import java.applet.*;
import java.awt.* ;
public class Ticker extends Applet implements Runnable {
   Additional functionality goes in here.
}

The first line is simply a comment line that describes the name of the Java applet. Any text enclosed between a /* symbol and a corresponding */ symbol is treated as a comment and is ignored by the compiler.

The next two lines of code—the ones starting with import—are used to tell the compiler about any additional class libraries that will be used by your applet. All applets need to use routines from the java.applet.* library, and to display information on-screen you also need routines from the Advanced Windows Toolkit, as defined by java.awt.*.

The fourth line of text is the one that does all the work of defining your new class as an applet. In this line, you declare the name for your new class—public class Ticker. You tell the system which existing class it is based on—extends applet. And because the Ticker Tape applet needs to run continually, you define a special package called Runnable by using implements Runnable.



Caution:

Make sure that you type the word Ticker in exactly the same way as you did when naming the Ticker.java text file. If the two names are not identical (case wise), Java will report an error when you attempt to compile the program.



Declaring Variables

Immediately after the class definition, you first need to define some variables for the applet to use. Like most object-oriented languages, Java is a typed language. As a result, you must declare the type of information that a variable will hold before it can be used.

To declare all the variables that are accessible to the entire class, make the following entry after the class declaration:

public class Ticker extends Applet implements Runnable {
    String tkident = "Ticker.class 3.0 Build 18"; /* class name and ident */
    Thread tkthread = null;     /* Thread handle needed for  multitasking */
    String tktext = "Exercise - ticker tape";          /* Default text    */
    int tkspd = 1;          /* The default scroll speed  (slowest is 1 ) */
    String tkfname = "TimesRoman";            /* The default font name   */
    int tkfsz = 12;                           /* The default font size   */
    Font tkfont = null;             /* Font handle for graphics library  */
    String tkdirection = "Left";        /* The default scroll direction  */
    Dimension tksize = null                  /* Window dimension handle  */
    int tktextwth = 0;                            /* Text width value  */
    int tktexthgt = 0;                             /* Text height value  */
    int tkpos = -63000;                        /* Scroll position   */
    Image tkImage;                           /* Image object for buffer */
    Graphics tkScreen;                      /* Graphics object for buffer*/

The init() Method

Inside every class, there can be any number of different routines called methods. These methods are used to control specific actions that can be taken by a class.

For every class, the first method called when the class is run (or instantiated) is the init() method. This method is used to set up default information for the class and to load variables like those just defined previously with working values. In the base applet class, an init() method is declared already; however, because you want to add additional functionality to the applet class, you need to override the base init() method with a new one of your own.

To define the init() method for Ticker and set up all the control variables, you write the code given next.



Note:

The comment lines included in this code are not required to make Ticker operate. They simply explain what each line does. If you are following along with this exercise, you need not include all the comments. Also, you might find it easier to refer to the completed example at the end of the exercise, which has all the comments removed.

Alternatively, you can download the complete source for this exercise from http://www.cnrstone.com/samsjsd.html. The source code also is on the CD-ROM.


/* Declare the init() method    */
public void init() {
/* Print the contents of tkindent to the Java console */
    System.out.println( tkident );
/* Declare a working variable for this method only                       */
    String getval = null;
/* Retrieve the text to be displayed by Ticker                           */
/* as defined in the HTML document                                       */
    getval = getParameter("tktext");
/* If no text is defined, revert to the default message                  */
    tktext = (getval == null ) ? tktext : getval;
/* Retrieve the scroll speed for Ticker                                  */
/*as defined in the HTML document                                        */
    getval = getParameter("tkspd");
/* If no speed is defined, revert to the default speed                  */
    tkspd = (getval == null ) ? tkspd : (Integer.valueOf(getval).intValue());
/* Retrieve the font for Ticker */
/* as defined in the HTML document                                       */
     getval = getParameter("tkfname");
/* If no font is defined, revert to the default font                    */
    tkfname = (getval == null) ? tkfname : getval ;
/* Retrieve the font size for Ticker  */
/* as defined in the HTML document     */
    getval = getParameter("tkfsz");
/* If no font size is defined, revert to the default size                */
    tkfsz = (getval == null ) ? tkfsz : (Integer.valueOf(getval).intValue());
/* Create a font class based on the font name and font size              */
    tkfont = new java.awt.Font( tkfname, Font.PLAIN, tkfsz ) ;
/* Check to see if the Reverse parameter has been set.                   */
/* If not, set tkdirection to Left                                       */
/* and tkpos to a large negative number                             */
/* Otherwise, set tkdirection to Right                                   */
/* and tkpos to a large positive number.                            */
    getval = getParameter("tkreverse");
    tkdirection = "Left";
    tkpos = -63000 ;
    if ( getval != null ) {
       if ( getval.equalsIgnoreCase( "Yes") ) {
          tkdirection = "Right";
          tkpos  = 63000;
          }
       }
/* Create double-buffering image area */
/* Get the size of the Java canvas                                        */
/* and assign it to a dimension class called tksize.                      */
    tksize = this.size();
/* Create a buffer to hold copy of the screen area */
    tkImage = createImage(tksize.width,tksize.height);
    tkScreen = tkImage.getGraphics();
}


Caution:

Be sure to include all the opening ({) and closing (}) brackets where listed. These curly brackets, or braces, are used by Java to indicate the start and finish of blocks of code, and without them, Java will get very confused indeed.



The start() and stop() Methods

The start() and stop() methods are called when a class is first started and when the class is stopped, as the names suggest.

In this exercise, the start() method needs to be overridden to define Ticker as a self-contained task, one that operates independently of all other activities on your computer. This action allows your operating system to better share its resources among all the programs that are currently running. If this is not done, there is a danger that a routine like Ticker could have a serious impact on the performance of other programs.

However, after you do define Ticker as a task, or thread of its own, you need a way to stop it from running when the applet is no longer needed. To do this, in the stop() method, you include a specific call to the thread to halt its execution.

The code required to perform the start and stop tasks follows:

/* Declare the start() method                                            */
public void start() {
/* Define a new Thread for this task                                     */
    tkthread = new Thread(this);
/* start Ticker running as an independent task                           */
    tkthread.start();
}
/* Declare the stop() method                                             */
    public void stop() {
/* stop the Ticker thread running                                        */
    tkthread.stop();
}

The run() Method

In the class definition at the start this exercise, you might recall a statement that said implements Runnable. What this statement actually does is define a template for a special method that gets called after the applet has been loaded, and following the init() and start() methods. If you have any computer programming experience, you'll find that the run() method is a bit like a main() subroutine.

For everyone else, at this stage all you really need to understand is that this method contains a loop of code that causes the Java screen to be continually redrawn. Each time it gets redrawn, the text in the Ticker window is moved a step to either the left or the right.

The code for the run() method looks like this:

/* Declate the run() method                                              */
public void run() {
/* Create an infinite loop that continually repaints the Java screen     */
    while (true) {
/* Redraw the contents of the Java applet window */
        repaint();
/* Then send Ticker to sleep so that other programs can get some work done */
        try {
            Thread.sleep( 100 );
        } catch (InterruptedException e){}
    }
 }

The update() Method

The update() method is used to control how the contents of the applet window are refreshed. Normally Java controls this process through an internal update() method, but to make the contents of a Ticker Tape window scroll smoothly it needs to be overridden with the following code.

/* Declare the updatet method                                              */
/* Unlike the other methods, this one receives some information from the  */
/* calling routine. This information is assigned to a graphics            */
/* class called g .                                                       */
public void update( Graphics g ){
/* call the paint() method with g as an argument  /*
    paint;
 }

The paint() Method

The final method for this exercise is the paint() method. Whenever the repaint() statement in the run() method is reached—each time through the while loop—the paint() method is the main method that gets run. The paint() method is where all the tricky stuff happens to make the text scroll across the screen.

In Java terms, the paint() method is where you draw information onto the Java canvas, which is a fancy name for the drawing area of a Java applet. The paint() method for Ticker looks like the following:

/* Declare the paint method                                               */
/* Unlike the other methods, this one receives some information from the  */
/* calling routine. This information is assigned to a graphics            */
/* class called tk.                                                       */
public void paint(Graphics tk) {
/* Set the font to use to the one defined in the init() method,           */
/* and then get its specs                                                 */
/* Note that the tkScreen buffer is used throughout this method instead   */
/* instead of the applet canvas tk.                                       *.
    tkScreen.setFont(tkfont);
    FontMetrics tkfm = tkScreen.getFontMetrics();
/* Calculate the height in pixels of the text,                            */
/* the first time through the paint method                                */
/* After this, use the previously calculated value.                        */
    tktexthgt = ( tktexthgt==0 ) ? tkfm.getHeight() : tktexthgt;
/* Calculate the width in pixels of the text message                       */
/* the first time through the paint method                                 */
/* After this, use the previously calculated value                         */
    tktextwth = ( tktextwth==0 ) ? tkfm.stringWidth( tktext ) : tktextwth;
/* If the scroll direction is set to Left,                                */
/* use the first set of calculations to determine the                     */
/* new location for the text in this pass through paint().                */
/* Otherwise, use the set of calculations following the else statement.   */
    if (tkdirection=="Left") {
       tkpos = ( tkpos <= tktextwth * -1 ) ? tksize.width : tkpos - tkspd;
       }
    else{
       tkpos = ( tkpos > tksize.width ) ? 0 - tktextwth : tkpos + tkspd;
    }
/* Set the color to white                                                  */
    tkScreen.setColor(Color.white);
/* fill the screen buffer tkScreen with the color white                    */
    tkScreen.fillRect(0,0,tksize.width,tksize.height);
/* Set the text color to black                                             */
    tkScreen.setColor(Color.black);
/* Draw the message in its new position on the Java canvas                 */
    tkScreen.drawString( tktext, tkpos, ( tksize.height + tktexthgt ) / 2 );
/* copy the contents of the screen buffer tkImage to the applet canvas     */
tk.drawImage( tkImage,0,0,this );
    }

Putting It All Together

As promised earlier, here is the completed Ticker applet, ready to be compiled. All the comments except the one on the first line have been removed, and any unnecessary line spacing is gone as well. The indentations, however, have been left in as a guide to how the various components are related. When you write Java code, using indentation to indicate the separate blocks of text is a very good way of cross-checking that no { or } symbols have been left out.

/* Exercise - Ticker.class */
import java.applet.*;
import java.awt.* ;
public class Ticker extends Applet implements Runnable {
    String tkident = "Ticker.class 3.0 Build 18";
    Thread tkthread = null;
    String tktext = "Exercise - ticker tape";
    int tkspd = 1;
    String tkfname = "TimesRoman";
    int tkfsz = 12;
    Font tkfont = null;
    String tkdirection = "Left";
    Dimension tksize = null;
    int tktextwth = 0;
    int tktexthgt = 0;
    int tkpos = -63000;
    Image tkImage;
    Graphics tkScreen;
 public void init() {
    System.out.println( tkident );
    String getval = null;
    getval = getParameter("tktext");
    tktext = (getval == null ) ? tktext : getval;
    getval = getParameter("tkspd");
    tkspd = (getval == null ) ? tkspd : (Integer.valueOf(getval).intValue());
    getval = getParameter("tkfname");
    tkfname = (getval == null) ? tkfname : getval ;
    getval = getParameter("tkfsz");
    tkfsz = (getval == null ) ? tkfsz : (Integer.valueOf(getval).intValue());
    tkfont = new java.awt.Font( tkfname, Font.PLAIN, tkfsz ) ;
    getval = getParameter("tkreverse");
    tkdirection = "Left";
    tkpos  =  -63000 ;
    if ( getval != null ) {
       if ( getval.equalsIgnoreCase( "Yes") ) {
          tkdirection = "Right";
          tkpos  = 63000;
       }
    }
/* Create double-buffering image area */
    tksize = this.size();
    tkImage = createImage(tksize.width,tksize.height);
    tkScreen = tkImage.getGraphics();
 }
 public void start() {
    tkthread = new Thread(this);
    tkthread.start();
 }
 public void stop() {
    tkthread.stop();
 }
 public void run() {
    while (true) {
        repaint();
        try {
            Thread.sleep( 100 );
        } catch (InterruptedException e){}
    }
 }
 public void update( Graphics g ){
    paint;
 }
 public void paint(Graphics tk) {
    tkScreen.setFont(tkfont);
    FontMetrics tkfm = tkScreen.getFontMetrics();
    tktexthgt = ( tktexthgt==0 ) ? tkfm.getHeight() : tktexthgt;
    tktextwth = ( tktextwth==0 ) ? tkfm.stringWidth( tktext ) : tktextwth;
    if (tkdirection=="Left") {
       tkpos = ( tkpos <= tktextwth * -1 ) ? tksize.width : tkpos - tkspd;
    } else {
       tkpos = ( tkpos > tksize.width ) ? 0 - tktextwth: tkpos + tkspd;
    }
    tkScreen.setColor(Color.white);
    tkScreen.fillRect(0,0,tksize.width,tksize.height);
    tkScreen.setColor(Color.black);
    tkScreen.drawString( tktext, tkpos, ( tksize.height + tktexthgt ) / 2 );
    tk.drawImage( tkImage,0,0,this );
 }
}

Compiling Ticker.java

After you have entered the code for Ticker.java into your text editor and saved a copy onto your hard drive, the next step in the process is compiling it into Java Byte-code.

To do this from either the DOS prompt or the UNIX command line, enter this:

javac Ticket.java


Note:

This assumes that javac is located somewhere in your execution PATH and that Ticket.java is located in the current directory. In addition, the HOME and CLASSPATH variables also need to be properly defined in your system environment. See the installation notes that came with the JDK for more information about setting the correct values for these variables.


If everything goes as planned, after a few seconds—or minutes, depending on the speed of your computer—your cursor will return to the command line, and a new file called Ticker.class will have been created in the current directory.

On the other hand, if the javac compiler detects any errors, you will see something that looks a bit like this:

C:\samsgold\java>javac Ticker.java
Ticker.java:15: ';' expected.
        Dimension tksize = null
                               ^
Ticker.java:49: ';' expected.
        this.setBackground( Color.white )
                                         ^
2 errors

The number following the colon indicates the line where the problem occurred, and the message after the number indicates the reason for the error. On the following line, the source for the problem line is displayed with a caret (^) indicating the fault's position in the line.

If you received any errors, go back and re-edit Ticker.java to fix the problems, and then try recompiling the applet. When you have a "good" compile of Ticker.class, you are ready to add the applet to your Web pages.

Learning More About Java


The fact that Java is a language that until very recently was somewhat unstable, to say the least, has made the job of writing a definitive text covering all the features of Java something akin to hitting a moving target. Luckily, however, things are now starting to change. Following the freeze of the Java specification at version 1.0, which was done in part to synchronize with the release of Navigator 3.0, the documentation and specifications for Java are now reasonably stable.

As a result of this stabilization, some very good tutorial documents, including the entire Java 1.0 API specification, are available online from Sun's Java Web site. To view any of this documentation or download a copy in either postscript or HTML form, point your Web browser to http://java.sun.com/doc/programmer.html, as shown in Figure 14.9.

Figure 14.9. http://java.sun.com/doc/programmer.html is a very good source of information about writing Java applets and applications.

Including Java Applets on Your Web Pages


After you have your new applet compiled, the next thing you will want to do is include it on a Web page to test it. In the final section of this chapter, you will learn how to include the Ticker-Tape applet on a Web page and how to include pre-built applets written by other people as well.

The <APPLET> Tag


When the <APPLET> tag is used on a Web page that is to be viewed using Navigator 3.0, it takes the following form:

<APPLET CODE="name.class" WIDTH=pixels HEIGHT=pixels></APPLET>

In the CODE attribute, you place the name of the Java class to be run, and in the WIDTH and HEIGHT attributes, you must declare the width and height of the drawing area (or canvas) to be used by the applet. In the current version of Navigator 3.0, if you do not include the WIDTH and HEIGHT attributes, the applet does not appear on the Web page at all.

Based on this information, you could include the Ticker-Tape applet in a Web page by writing the following:

<APPLET CODE="Ticker.class" WIDTH=400 HEIGHT=75></APPLET>

In this basic form, when you loaded the Web page, the Ticker applet would be displayed by using the default values set in the init() method discussed previously.



Note:

So that your Web browser can locate the applet code, place the Ticker.class file in the same directory as the Web page.



The <PARAM> Tag


In the init() method of Ticker.class, several calls were made to a method called getParameter(). What this call actually does is interrogate the <APPLET> tag, looking for parameters that match the name declared in the getParameter() call, as shown here:

getval = getParameter("tktext");
tktext = (getval == null ) ? tktext : getval;

In this example, getParameter("tktext") tells Java to look for a parameter called tktext between the <APPLET> and </APPLET> tags. If such a value is located, the text associated with the parameter, rather than the default message text, is scrolled through the Ticker Tape window.

To define tktext as a parameter inside the <APPLET> tags, you use the <PARAM> tag, which takes the following form:

<PARAM NAME="tktext" VALUE="Exercise - Scroll this text in the Ticker Tape window">

When used inside the <PARAM> tag, the NAME attribute is assigned the parameter name, and the VALUE attribute is assigned the information to be passed to the applet.

If you take a closer look at the init() code, you'll see four other parameters that can also be set for Ticker.class:

By combining these attributes, you can tailor the appearance of the ticker-tape window in various ways. For example, when they're used as shown in the following HTML source, the result is a Web page like the one shown in Figure 14.10.

<HTML>
<HEAD>
<TITLE>Exercise - Ticker.class</TITLE>
</HEAD>
<BODY>
<H1>Ticker Tape Java Exercise</H1>
<HR>
<P ALIGN=CENTER>
<APPLET CODE="Ticker.class" width=400 height=50>
<PARAM NAME="tktext"
       VALUE="Exercise - Scroll this text in the Ticker Tape window">
<PARAM NAME="tkspd"     VALUE="1">
<PARAM NAME="tkfname"   VALUE="Arial">
<PARAM NAME="tkfsz"     VALUE="28">
<PARAM NAME="tkreverse" VALUE="Yes">
</APPLET>
</P>
<HR>
</BODY>
</HTML>

Figure 14.10. Ticker.class adds a scrolling ticker tape window to your Web pages.

Building on the Ticker Example


With a little extra work, you can add many other features to Ticker.class, if you wish. These could include parameters to control the color of the text or background, the ability to display text from a separate HTML document in the Ticker-Tape window, or even fancy borders like those in the ticker-tape window shown in Figure 14.1, at the start of this chapter.

You might be surprised to hear that some good examples of enhanced Ticker-Tape classes are already available for download from sites on the World Wide Web—saving you the hassle of coding all these features yourself. To locate most of these sites, take a look at the Gamelan directory mentioned previously—http://www.gamelan.com/.



Note:

Many of the Java classes currently available include source code you can freely use in your own applets. Before using anyone else's code, however, check the copyright requirements the author expects you to meet. Some authors ask for mention and possibly a hyperlink to their site, whereas others expect nothing.



Using Pre-built Java Applets


If you're starting to feel as though this Java thing is a bit beyond you—maybe the preceding pages look more like a Chinese lottery ticket to you than a computer program—or you just feel as though you don't have the time to spend learning all its intricacies, you might be interested in an alternative way to use Java. This method provides many of the benefits without most of the programming hassles.

The distributed nature of Java means that it is possible to incorporate Java applets that have been developed by other people into your Web pages. In addition, in some cases you don't even need a copy of the Java class on your own computer; you only need to know where it is located.

For example, an enhanced version of the Ticker-Tape class you learned about previously is stored on my Web site at http://www.cnrstone.com/TickerT.class. To use this class in your own Web pages, you have two options. You can download the class by using FTP and install it at your own Web site, or you can simply include the location of the class as part of your <APPLET> tag. If used in this second form, the <APPLET> tag will look something like the following:

<APPLET CODE="TickerT.class" CODEBASE="http://www.cnrstone.com/" HEIGHT="30" WIDTH="400" >

The difference between this example and previous ones is in the inclusion of the CODEBASE attribute, which contains a URL that describes the location of the directory where the Ticker.class file is located.



Note:

To find out about the latest features of TickerT.class, point your Web browser to http://www.cnrstone.com/TickerT.html. This page contains information about the supported parameters and describes how you can download the file yourself. All I ask is that if you do decide to use this applet on your Web pages, please include a link to my home page at http://www.cnrstone.com/ as described on the page listed previously.


A quick exploration of the Gamelan site reveals various other sites that also offer classes you can incorporate into your own Web pages. Take, for example, the J_tools site shown in Figure 14.11. This collection includes applets that display animated bullets, multicolored wavy text, and different types of horizontal rules. To find out more about how you can use these applets in your own pages, take a look at http://www.crl.com/~integris/j_tools.htm.

Figure 14.11. J_tools is a collection of Java applets that enable you to display animated bullets, text, and rules on your Web pages.

A copy of the J_tools applet class has been included on the CD-ROM that accompanies this book, along with a collection of sample applets for you to experiment with. The following list indicates who created each applet.

Jumping Frog Applet

Charles-Edouard Ruault, Association Decouvertes, Paris, France


Stock Trace Applet

Christian Dreke, University of Virginia Networks Laboratory, Charlottesville, Virginia


Chernobyl Reactor Applet

Henrik Eriksson, Ph.D., Linköping University, Sweden


Server Socket Example Applet

Mike Fletcher, Bell South Wireless, Atlanta, Georgia


Clock and GoURL Applets

Nils Hedström, Linköping University, Sweden


Curve Applet

Michael Heinrichs, Burnaby, BC, Canada


Learn to Dance Applet

Georg Heßmann, University of Hamburg, Germany


J-Tools Applet

Gene Leybzon, Integris, Clayton, Missouri


Documentation, Form, Jline, Pointer, Ticker, & WAIS Interface Applets

Thomas Wendt, Univ. of Kessel, Germany


Collections (A Collection of Functions and Utilities)

Doug Lea, SUNY at Oswego, New YorK


Summary


As you have discovered in this chapter, Java has the potential to forever change the face of Web publishing, but at the same time, its some effort is required to come to grips with its capabilities. This having been said, at the same time, Java applets are remarkably easy to incorporate into your Web page. All it takes is an <APPLET> tag and a few corresponding <PARAM> tags.

To learn more about what Java has to offer, point your Web browser to http://java.sun.com/, and join the journey into the next generation of Web publishing.

There is another aspect of Java that has not yet been examined in detail. This is the fact that Java applets and JavaScript programs can be made to interact with each other and share information and commands. The next chapter examines how JavaScript and Java communicate with each other.

Previous Page Page Top TOC Next Page See Page