Chapter 8

Developing Applets and Applications

by Bryan Morgan


CONTENTS

This introduction to Java programming with Visual J++ concludes with a discussion of Java applet and application development. This chapter is important for several reasons, the most important of which is that by the time you reach the end, you will have created a real, live Java applet and application. You are almost ready to produce some visible Java code to show your friends, boss, cellmates, and so on.

This chapter opens with a discussion of the similarities and differences between applets and applications-a topic of unending confusion. In fact, most users of Java applets within Web pages do not know that they can use Java to create standalone applications as well.

A Comparison of Applets and Applications

Many people still think that the words Java and applet are synonyms that mean a type of interactive program that runs within a Web browser's window. The reason for this misconception is that, despite Java's rapid growth, nearly all visible examples of Java code are in the form of applets running within Web pages. However, it is completely possible to build a standalone Java application that can run without the help of a Web browser. In fact, Java applications can be written to duplicate standard Windows, Mac, or UNIX applications; that is, Java applications can have a main window; include a GUI that uses menus, buttons, lists, and text boxes; and can access databases in various ways. With the advent of Visual J++, Java applications can even use existing ActiveX controls, the same way that Visual Basic and Delphi applications do today.

On the other hand, don't underestimate the importance of Java applets! Many people believe that the Web browser will be the next generation in user interfaces, and applets play a key role in the success of that interface. An incredible number of corporate applications that were once written in Visual Basic, PowerBuilder, or Delphi are currently being written to run as intranet applications using HTML, Java, and CGI scripts. In addition, the volume of Java applets currently on the Web vastly outnumbers the Java applications in existence today. With the introduction of Visual J++, however, Java should be a viable candidate for rapid application development (RAD) due to its powerful IDE, the numerous wizards available to the programmer, and its support for ActiveX controls. Because of these advantages, the number of people using Java for application development will undoubtedly grow.

Several unique features set Java applets apart from every other type of computer program:

Java applications, meanwhile, have none of the above restrictions. An application could be written to run within a window, but it is not required. The first application you will write runs only from the command line and performs simple text input and output. Currently, Java applications have the disadvantage of requiring a runtime Java interpreter, but soon Java applications will be able to be compiled to binary form and run as executables (EXE files).

Building a Java Application

As mentioned earlier, Java applications are programs that can run without the aid of a Web browser (or some other viewing application such as Sun's applet viewer). A Java application is able to read and write local files, display windows, access remote servers, and play multimedia objects.

Java applications have one coding requirement: They must supply a method named main() similar to the following:


public static void main(String args[])

{

  /* Include statements here */

}

C and C++ programmers will recognize that this method was borrowed directly from the C/C++ languages. When the Java application is first started, the interpreter immediately looks for a main() method. If none exists, the program cannot run.

The main() method is the entry point for the entire application. In general, this method is where the main objects for the application are created and initialized. If the primary application window is to be displayed to the user, it will be created and displayed within the main() method. In other words, all other methods and classes within the application feed off the startup code placed within main().

The Inevitable Hello, World! Application

At this point, you are finally ready to begin serious application development using Java. You should feel comfortable with the Visual J++ environment, have a working understanding of the Java language, and be able to run the Java interpreter either within Visual J++ (which requires no special setup) or from the command line (as discussed earlier). The first example illustrates the process of creating a new project, adding source code, compiling the project, and running the application.

Visual J++ does not require you to create new classes and store them within a project. However, the project files will be created for you anyway the first time you try to compile a class.

The goal of the following example is to create a simple Java application that prints the text Hello, World! to an output device. In this case the output device is the MS-DOS console window. After starting Microsoft Developer Studio, select the File | New...menu option. The New dialog box contains selections for creating a new text file, project workspace, resource template, and bitmap file. Because this step is the start of a new application project, select Project Workspace.

Within the New Project Workspace dialog box, you will concentrate on creating a Java workspace (the Java Applet Wizard is covered in Chapter 11, "Building a Simple Java Applet with Visual J++"). Name the project "HelloWorld" and select the directory to create the project in. This step creates a subdirectory within the specified directory, which is named HelloWorld and will contain the HelloWorld project workspace files (HelloWorld.mak and HelloWorld.ncb).

Notice also that the HelloWorld project workspace is now loaded in the ClassView and FileView windows (see Figure 8.1), although it contains no source files yet.

Figure 8.1 : The empty HelloWorld project in Visual J++.

To add a class to the project, right-click over the root note ("HelloWorld classes") in the ClassView and select Create New Class.... In the Create New Class dialog box, enter HelloWorld as the class name and leave everything else blank at this time. Click the OK button, and the following code will be created for you in a source file named HelloWorld.java:


/*

 *

 * HelloWorld

 *

 */

class HelloWorld

{



}

Note
Visual J++ went ahead and named the source file for you because Java source files must be named after the public class within the source file. (Recall that each source file in Java can have only one public class.) Because this source file has only one class, HelloWorld, the file was named HelloWorld.java by default.

To cause the text Hello, World to be printed to the screen, you must create a main() method. Once this method has been declared, a single line of code will suffice to print to the screen. Modify the HelloWorld class by adding the following code:


/*

 *

 * HelloWorld

 *

 */

class HelloWorld

{

  public static void main(String args[])

  {

    System.out.println("Hello, World!");

  }

}

After saving the source file, notice that ClassView was automatically updated with the new main() method (see Figure 8.2).

Figure 8.2 : The new main() method displayed in ClassView.

Before compiling and running this project, you will need to modify one project setting. By default, all Visual J++ projects use a Web browser as a debugger. Because, in this case, you want to view the output in the MS-DOS window, select the Build|Settings... menu and then select the Debug tab. Within the Execute project under group box, select Standalone interpreter (applications only) and press OK. Now you're ready to go!

To compile and run this simple application, select the Build | Build HelloWorld menu option or press Shift+f8. If the project compiles with no errors, run the application by selecting the Build|Execute menu option or by pressing Ctrl+f5. When prompted, enter the name of the project's main class file (HelloWorld.class) and watch the program run. The following text should appear in the output window briefly before the window closes:


Hello, World!

You have just built your first Java application using Visual J++. The System.out class's println() method was used to print a line of text output to the system window. The next section explains where the System object came from.

The java.lang.System Class

In the HelloWorld example, the java.lang.System class was used but was never declared anywhere in the main() method or in the HelloWorld class. It didn't have to be declared because the System class is created by default at runtime and is available to all running Java applications and applets. All methods and variables within this class are static; therefore, the System class cannot be instantiated or subclassed. It contains three variables used for streaming input and output:

In addition to these member variable classes (and their members), the System class provides a number of useful methods including

The in object is of type InputStream and does not need to be created. This class is most commonly used to respond to keyboard input from the user. The out object is of type PrintStream and is most commonly used to display textual output to some system output device such as the MS-DOS prompt under Windows.

Creating a Graphical Application

The HelloWorld application provides a good opportunity to introduce the steps required to create and build a new project. However, the actual code accomplishes very little from a visibility standpoint. (Below the surface, of course, a lot of work was done. The HelloWorld.class file can be run on any computer in the world with a JVM installed, which includes 3.1/95/NT, Macintosh, UNIX, and IBM AS/400.) The purpose of this section is to produce a graphical example using menus and graphical output in the form of a Java application. This section is not intended to be a tutorial on GUI programming with Java. That topic is discussed in detail in Chapter 14, "An Introduction to GUI Programming."

Listing 8.1 shows the MenuApp application.


Listing 8.1. The MenuApp application.

import java.awt.*;

import java.lang.String;



/*

 *

 * MenuApp - A GUI app that prints text to the screen

 *           based on a user's menu selection

 *

 */



class MenuApp extends Frame

{

  MenuBar theMenuBar;

  Menu theMainMenu;

  String PaintString = "MenuApp V1.0";



  MenuApp(String str)

  {

    super(str);

  }



  void SetUpMainMenu()

  {

    /* Create the main menu and add items to it */

    theMenuBar = new MenuBar();

    theMainMenu = new Menu("Print");



    theMainMenu.add(new MenuItem("Hi There!"));

    theMainMenu.add(new MenuItem("Kick Me!"));

    theMainMenu.add(new MenuItem("Cooooool!"));

    theMainMenu.add(new MenuItem("What's Up?"));

    theMainMenu.add(new MenuItem("-"));

    theMainMenu.add(new MenuItem("Exit"));

    theMenuBar.add(theMainMenu);

  }



  public static void main(String args[])

  {

    MenuApp theFrame;

    theFrame = new MenuApp("Visual J++ Unleashed MenuApp");

    theFrame.SetUpMainMenu();

    theFrame.setMenuBar(theFrame.theMenuBar);

    theFrame.resize(320,240);

    theFrame.repaint();

    theFrame.show();

  }



  public boolean action(Event evt, Object arg)

  {

    if (evt.target instanceof MenuItem)

    {

      String str = (String)arg;

      if (str.equals("Exit"))

      {

        dispose();

        System.exit(0);

        return true;

      }

      else

      {

        PaintString = str;

        repaint();

      }

    }

    return false;

  }



  public void paint(Graphics g)

  {

    int X = 160;

    int Y = 120;

    int CharWidth;

    int CharHeight;



    FontMetrics metrics = g.getFontMetrics();

    CharWidth = metrics.charWidth('A');

    CharHeight = metrics.getHeight();



    X -= CharWidth * PaintString.length() / 2;

    Y -= CharHeight / 2;



    g.drawString(PaintString, X, Y);  }

}


The application in Listing 8.1 (MenuApp) includes the following member methods:

The MenuApp application can be seen running in Figure 8.3.

Figure 8.3 : The MenuApp application running in Windows 95.

This application makes use of quite a few of the classes available in the Java package included with every JVM (including the Microsoft Windows Virtual Machine used by the Visual J++ runtime interpreter, JView). For information on any of the imported classes' member methods called within MenuApp, consult the Visual J++ documentation. Classes used within the MenuApp class include java.awt.MenuBar, java.awt.Menu, java.awt.MenuItem, java.lang.String, java.awt.Event, java.awt.FontMetrics, and java.awt.Graphics. You could have written the following statements to import the classes used by the MenuApp class:


import java.awt.MenuBar;

import java.awt.Menu;

import java.awt.MenuItem;

import java.lang.String;

import java.awt.Event,

import java.awt.FontMetrics;

import java.awt.Graphics;

However, it is easier to simply write the following:


import java.awt.*;

This tells the compiler to import all public classes in the java.awt package. Most Java developers import all java.awt classes whenever they are programming with the Abstract Windowing Toolkit, that is, GUI programming. This shorthand is much quicker than continually going to the top of a source file and adding class files one by one.

This concludes the section on developing Java applications. The key point is that all Java applications are required to supply one static main() method. This method is responsible for initializing and creating objects for use throughout the program.

Running Your Application with the Standalone Java Interpreter

Java programmers already experienced in programming with the Java Developer's Kit (JDK) may be familiar with its Java runtime interpreter. Under Windows 95/NT, this interpreter existed in the form of the file java.exe and would run an application using the following command-line command:


java main_class_name

After you pressed Enter, the application's main class could be run and the application would be started.

Visual J++ provides two different options for running Java applications:

These options give the same result, but some users prefer to develop using command-line syntax; therefore, jview.exe is discussed briefly here. Even if you plan to develop solely within Visual J++, keep in mind that when you distribute your application, it will not run without the aid of a runtime interpreter such as Microsoft's jview.exe. Therefore, if you plan to program in J++, you should understand how to set up the runtime interpreter.

Note
When you run a Java application from within Visual J++, no setup needs to be done because Visual J++ calls JView with the correct options. However, calling JView directly requires the user to configure these options manually.

You will find the jview.exe file in the \msdev\bin directory of the Visual J++ installation. (Don't bother trying to run it at this point. It will not do anything useful without an accompanying Java class name on the command line.) To correctly use JView as a Java interpreter for your application, you need to do two things:

Modifying the System Path

To set the path to jview.exe under Windows 95, simply open the AUTOEXEC.BAT file and modify the PATH environment variable. If jview.exe resides in the C:\windows\java\bin directory, add the following line to AUTOEXEC.BAT:


SET PATH=%PATH%;C:\WINDOWS\JAVA\BIN

(The %PATH% setting simply concatenates the current path with the string you are adding to it.) After rebooting, any program within this directory (including jview.exe) can be executed from anywhere else on your system.

Modifying the CLASSPATH Environment Variable

Before the interpreter can run any Java application, it needs to know the location of all the Java class libraries you used so that it can link your application's classes together with these additional classes. (For instance, if you derived your application class from the java.awt.Graphics class, JView would need to know the location of the java.awt.Graphics.class file.)

This information is stored in an environment variable known as CLASSPATH. All Java interpreters use the CLASSPATH variable to retrieve a search path for class files. As you did for the PATH environment variable mentioned previously, you can modify CLASSPATH by modifying the variable within the AUTOEXEC.BAT file. The Visual J++ class library is included entirely within a file named classes.zip.

Note
Class files can exist as single files or they can be grouped together within a ZIP file. Java interpreters must be able to locate class files using either method.

If this classes.zip file were installed in your C:\windows\java\classes directory, the CLASSPATH should be set to


SETCLASSPATH=%CLASSPATH%;C:\WINDOWS\JAVA\CLASSES\CLASSES.ZIP

If the contents of the classes.zip file were extracted into the C:\windows\java\classes directory, the CLASSPATH could instead be set to


SET CLASSPATH=%CLASSPATH%;C:\WINDOWS\JAVA\CLASSES

Now that the path to jview.exe and the Java class library have been set, you are ready to run Java applications from within Visual J++ or from the command-line prompt. It is now up to you to decide how to execute any Java applications you create throughout the remainder of the chapter.

Limitations of Java Applets

Unlike applications, Java applets cannot control their own destiny. Applets, by definition, are instantiated Java classes that run within another viewing environment. This environment is nearly always a Web browser such as Microsoft Internet Explorer 3.0 (or higher), Netscape Navigator 2.0 (or higher), or Sun's HotJava. Figure 8.4 shows the BouncingHeads sample applet running inside Microsoft Internet Explorer 3.0.

Figure 8.4 : The BouncingHeads applet.

Applet-aware Web browsers are available (or will be soon) on a variety of platforms, including

Although this list is by no means comprehensive, it does encompass more than 98 percent of the personal computing market. Therefore, you can probably assume that anyone you are writing software for has access to at least one of the operating systems listed. Contrary to what you may think, Java applets (and Web browsers, for that matter) do not require an Internet connection. All sample applets included with Visual J++ and with this book should run fine without a network connection. The only exception to this rule is applets that attempt to do things such as retrieve files from a remote server, perform networking operations, or load new Web pages into the browser.

Applet Security Limitations

Applets do not require the user to have a Web connection; however, most Web browsers put severe restrictions on Java applets to keep them from performing potentially harmful acts on the user's system. For instance, with the power of the classes included in the Java package, a rogue Java applet could retrieve all files from your local file system that begin with the letters budget and could send them over the Internet to a remote server. (This action is completely possible with ActiveX controls.) Web browsers such as Netscape Navigator and Microsoft Internet Explorer disallow applets from accessing the local file system. (Both Netscape Navigator 3.0 and Microsoft Internet Explorer 3.0 restrict the user to turning on or off the capability of loading Java applets.)

In addition to Java security features built into popular Web browsers, the Java runtime environment and Java language are both designed to provide an extremely high level of security. Because Java applets can in no way directly access memory through pointers and because they are unable to access the local system, the vast majority of security problems are eliminated.

Inter-Applet Communication Limitations

Java applets are also somewhat limited in that they are, by default, unable to communicate with applets in other browsers, and in some cases, even with other applets on the same page. As you will see, Microsoft ActiveX allows applets and ActiveX controls to be scripted together using JavaScript or VBScript, which enables objects on a Web page to communicate with each other. However, this proprietary solution works only in the Microsoft Web browser. Likewise, Netscape has announced its Open Network Environment (ONE) initiative that will provide a framework for applets to communicate with each other and with distributed CORBA (or Common Object Request Brokering Architecture) objects, using an Object Request Broker (ORB) that will be packaged with Netscape Navigator 4.0. However, once again this proprietary solution will work only within the Netscape browser. The development community has expressed some concern that the "open" days of the Web may be long gone. Just as the operating system war was beginning to look like a thing of the past, the Web browser has, in effect, become the operating system. If you want your software to provide active content in the form of Java applets or ActiveX controls, you will have to do some careful planning to ensure that your software reaches the broadest audience.

Building a Java Applet

As you already know, from an "external" viewpoint Java applets require two things:

The rest of this discussion assumes that you have a Java-aware browser. The <APPLET> tag is described in detail in Chapter 11 and Chapter 29, "Embedding Components Within Web Pages."

From an "internal" viewpoint, Java applets must derive themselves from the java.applet.Applet class. The Applet class itself is derived from the java.awt.Panel and therefore by default is always displayed as a plain white rectangle within the boundaries specified for it in the <APPLET> HTML tag. The Applet class contains five methods that are extremely handy when building your own Java applet: init(), start(), stop(), destroy(), and paint(). Keep in mind that applets are not required to supply a main() method. If this method is supplied, it will be ignored by the Java runtime environment and never called.

The init() Method

The init() method is called automatically whenever an applet is loaded within a Web page. This method provides a convenient location for the creation and initialization of applet variables and other setup tasks. The method definition for the init() method looks like this:


public void init()

{

  /* Add statements here */

}

The start() Method

The start() method is always called after the initialization is completed. Although the init() method is called only when the page is loaded, the start() method is called each time the page is loaded and each time the page is restarted. A page can be stopped when a user goes to another page. When the user returns to the original page, the start() method is called again, whereas init() is not. The signature for the start() method is


public void start()

{

  /* Add statements here */

}

The stop() Method

The stop() method is called whenever the Web browser user leaves a page to go to another page. If you are performing any sort of animation or memory-consuming activity, always be sure to implement the stop() method to avoid wasting system resources. When the user returns to your page, the start() method will be called. The signature for the stop() method looks like this:


public void stop()

{

  /* Add statements here */

}

The destroy() Method

The destroy() method is called immediately before the applet exits. This exit operation could occur because the applet requested it, or it could occur because the Web browser was being shut down. Unless you need to deallocate some type of resource, you probably will not implement the destroy() method as often as you implement init(), start(), stop(), and paint(). The signature for the destroy() method looks like this:


public void stop()

{

  /* Add statements here */

}

The paint() Method

The paint() method is used to draw items onto the applet's window. As you saw in Listing 8.1, the paint() method is called each time the repaint() method is called in order to repaint the applet. The signature for the paint() method looks like this:


public void paint(Graphics g)

{

  /* Add statements here */

}

The Hello, World! Applet

Like the HelloWorld application built at the beginning of the chapter, the HelloWorldApplet applet can be written in just a few lines of code. Follow the same steps to create a project workspace for this applet that you followed to create the HelloWorld application. When the workspace is ready, create a new class named HelloWorldApplet and derive it from the java.applet.Applet class.

Note
If you type in the parent class name incorrectly, Visual J++ will prompt you. It quickly scans all the classes available in the CLASSPATH and determines whether the class you asked for is available.

To draw the words Hello world! onto the screen, all you have to do is put the correct draw commands in the paint() method. Therefore, every time the paint() method is called, these words will be drawn to the applet's canvas. Listing 8.2 builds HelloWorldApplet.


Listing 8.2. The HelloWorldApplet applet.

import java.applet.Applet;

import java.awt.Graphics;



/*

 *

 * HelloWorldApplet

 *

 */

class HelloWorldApplet extends Applet

{

  public void paint(Graphics g)

  {

    g.drawString("Hello world!", 10, 25);

  }

}


Once this code is compiled and run, the text Hello world! will be drawn within the applet (see Figure 8.5).

Figure 8.5 : HelloWorldApplet within Microsoft Internet Explorer 3.0.

The default font used by Internet Explorer is almost too small to read. The code in Listing 8.3 uses the Graphics class setFont() method to enlarge the font to a more readable size. This method is called within the applet's init() method and is therefore called when the applet is initialized.


Listing 8.3. The HelloWorldApplet2 applet.

import java.awt.Font;

import java.awt.Graphics;



/*

 *

 * HelloWorldApplet2

 *

 */

public class HelloWorldApplet2 extends java.applet.Applet

{

  Font tempFont;



  public void init()

  {

    tempFont = new Font("Helvetica", Font.PLAIN, 30);

  }



  public void paint(Graphics g)

  {

    g.setFont(tempFont);

    g.drawString("Hello world!", 10, 25);

  }

}


Figure 8.6 shows the HelloWorldApplet2 applet displayed with a much larger font (Helvetica 30-point).

Figure 8.6 : The HelloWorldApplet2 applet says Hello world! more clearly.

Note that Visual J++ automatically creates default HTML files whenever your default debug viewer is set to Browser. (Remember that tags must exist within an HTML file to tell the browser which class file to load.) The contents of the HTML files and the <APPLET> tag in particular are discussed later in the book. Listing 8.4 shows the contents of the HTM file created for the HelloWorldApplet2 applet by Visual J++.


Listing 8.4. The HTML created by Visual J++ for HelloWorldApplet2.

<html>

<head>

<title>HelloWorldApplet2</title>

</head>

<body>

<hr>

<applet>

code=HelloWorldApplet2

width=200

height=200>

</applet>

<hr>

</body>

</html>


This HTML file contains two primary pieces of information: the title to be displayed at the top of the screen and the applet location and size information. Note that the <title> tag is HelloWorldApplet2 . The <applet> tag contains three required pieces of information:

Chapter 26, "HTML and Web Page Design," and Chapter 27, "Manipulating Web Components Using JavaScript," provide the information you need to modify the HTML generated by Visual J++ in order to enhance your page's appearance.

Summary

Many programmers do not know that they can use Java for purposes other than Web page enhancements. In fact, Java is a full-featured, powerful programming language that is supplied with a large cross-platform class library. Java applications have full access to the local system (no security restrictions) and can use the normal GUI components available to Java applet developers. Java applications are differentiated from applets in that applications must supply a main() method.

Java applets, meanwhile, are designed to be run only within Java-aware Web browsers. Because of the security problems inherent in a large network like the Internet, Java applets are commonly subjected to security restrictions. HTML files contain tags to tell the browser which Java class file to access in order to run the applet. Commonly implemented class methods include init(), start(), stop(), destroy(), and paint().

This chapter concludes Part I, "Introduction to Java Programming Using Visual J++." Part II, "The Visual J++ Development Tools," focuses exclusively on the many development tools that ship with the Visual J++ product. These tools include an extremely fast compiler, a visual debugger, numerous wizards to aid in development, advanced project management features, and a large library of standard Java classes.