Special Edition Using Microsoft® Visual Studio for Enterprise Development

Previous chapterNext chapterContents


- 7 -
Creating Components with Visual J++

by Azam A. Mirza

Learn about creating Java applets and applications with Visual J++. Learn about creating projects, building individual modules, building the applet, and using user interface elements.
Learn about testing your application with Internet Explorer or another Java-compliant browser. Understand the differences between applications and applets.
Learn to how to debug a Visual J++ applet using the Visual Studio integrated debugging environment and how to make changes and enhancements to your applets.
Learn how you can use the Applet Wizard and the Resource Wizard to create a template for your projects that you can work from and customize to your needs.

The Microsoft Visual J++ environment is an Integrated Development Environment (IDE) for building Java applets and applications. Visual J++ shares the Developer Studio IDE with Visual C++ and Visual InterDev. The Developer Studio IDE provides a one-stop shop for building, testing, and debugging Visual J++ programs.

The Visual J++ system not only leverages the IDE to provide a visual environment for building Java applets, but it also includes a very fast compiler, a powerful debugging mechanism, a resource editor, and wizards to get you productive with the least amount of overhead. The Visual J++ environment uses the concept of a project workspace to organize development efforts. You work by creating and adding files to the project that houses the program.

This chapter is not a discussion of the Java language, but instead an introduction to using the Visual J++ language to create Java applets that can be used to enhance your web development efforts. This chapter assumes that you, the developer, are familiar with the Java language specification and have a basic understanding of software development principles and concepts.


TIP: It is possible to build a Visual J++ applet and use it in a Visual InterDev project, all within the same workspace.


NOTE: If you would like to learn about the Java language, refer to the Java Language Specification or the Java Application Programming Interface included in the online documentation provided with Visual J++. You can also use the sample applications and applets provided with Visual J++ to familiarize yourself with the Java language and the Visual J++ environment.

Creating a Java Applet or Application

Visual J++ can create two kinds of Java programs: an applet or an application. The primary difference between an applet and an application is that an applet runs in the context of an HTML page inside a Java-capable browser, such as Microsoft Internet Explorer, whereas an application can run on its own using a standalone Java language interpreter. In terms of developing an applet or application, there are a few differences that must be kept in mind when working with Visual J++. These differences include the following:


NOTE: A Java-capable browser is one that provides support for interpreting the Java language through a Java virtual machine. Examples include Internet Explorer and Netscape Navigator.


TIP: You can provide a graphical front end for an applet that runs as an application by deriving the application class from the Frame window class in addition to the Applet class. The Frame window class is used only when an applet is run as a standalone application.

To create an applet using Visual J++, you must first create a project that will host the development. You can then create, add, and modify project files that host the class modules, the resource files, and even the HTML file that might host the Java applet. The following sections discuss each of these activities in further detail.

Creating the Project Workspace

As stated earlier, the Visual J++ environment uses project workspaces to keep track of the class files in a project. To create a project in Visual J++, take the following steps:

1. Start Visual J++ and select New from the File menu.

2. The New dialog box appears. Click the Projects tab, as shown in Figure 7.1.

FIG. 7.1
The New tabbed dialog box is part of the Visual Studio shared IDE that can be used to create files of various types.

3. Select Java Project.

4. Provide a name for your project in the Project Name box.

5. In the Location text box, provide an alternative location for the project directory or select the default location.

6. Click OK. Visual J++ will create a new project in the directory specified.

The IDE provides two Explorer-style views into the Visual J++ project:


See "Using Developer Studio," Chapter 2

When you create a project using the method described in the preceding six steps, the system creates a project that is used to create a single Java applet or application. The system by default creates a scenario for building two kinds of Java applets, a debug version and a release version.

Adding Files to the Project

After you have created the project, you will have a skeleton workspace with just the project defined in it. You can now create files in the project or add files from other Java projects by using file drag-and-drop techniques.

To add a new file to the project, take the following steps:

1. Select New from the File menu and click the Files tab. The Files dialog box appears, as shown in Figure 7.2.

FIG. 7.2
You can create a Java file by selecting the Java Source File or the Text File option from the list.

2. Select Java Source File from the list.

3. Provide a name for the Java Source File in the File Name text box.

4. Click OK. Visual J++ will create and add an empty text file to the project.

Now that you have added a source file to the project, you can add code to the file to build your Java applet.

Building the Applet

A Java source file is a text file that you can edit in the Visual Studio source editor. Try creating a simple Java applet that displays the famous "Hello World" caption in a web page as a Java applet. To build the Java applet and run it in a browser, take the following steps:

1. Double-click the Java source file in the FileView Explorer to open it in the source editor.

2. After the file is open in the source editor, add the following lines of code:
import java.awt.Graphics;
public class HelloWorld extends java.applet.Applet
{
    public void paint( Graphics g )
    {
        g.drawString( "Hello Java World.", 10,20 );
}
}
3. After you have typed the code, save the file by selecting Save from the File menu.

4. To run the applet, select Execute from the Build menu. The Information For Running Class dialog box will appear, as shown in Figure 7.3.

FIG. 7.3
The class filename tells the Visual J++ compiler which class you are trying to execute.

5. Type the class filename as HelloWorld and click OK. The class filename must exactly match the class name you declare within the code, or the applet will not run.

6. Visual J++ will launch Internet Explorer and display the Java applet in an HTML file that it creates for testing purposes, as shown in Figure 7.4.

FIG. 7.4
You can use any Java-compliant browser, such as Internet Explorer, to test the Java applet.


TIP: To change the default browser from Internet Explorer to another browser, go to the Debug tab in the Project Settings dialog box, select the Categor_y of Browser, and change the Browser path to the executable file for the new browser.
7. View the applet and then close the browser and return to Visual J++.

You can also create your own HTML file for testing purposes. To create your own sample HTML testing file, complete the following steps:

1. Select New from the File menu.

2. Select HTML Page from the Files tab and type HelloWorld as the filename in the text box, as shown in Figure 7.5.

FIG. 7.5
The integrated environment allows you to easily add an HTML file to a Visual J++ project.

3. Click OK and a sample HTML file will be added to your project.

4. Double-click HelloWorld.htm to open it in the source editor and add the following lines of code where it says, <!-- Insert HTML here -->:
<applet code="HelloWorld.class" WIDTH=200 HEIGHT=50>
</applet>
In the preceding code lines, the code tag identifies the Java class file to run for the applet. The height and width properties define the size of the applet in the web page.

5. Save the HTML page.

6. From the Project menu, select the Settings menu option. The Project Settings dialog box displays.

7. From the Debug tab, select Browser in the Categor_y drop-down listbox (see Figure 7.6).

FIG. 7.6
The Project Settings dialog box is used to set various options for your Visual J++ project.

8. Select Use Parameters from HTML Page and enter HelloWorld.htm in the HTML Page text box.

9. Click OK to continue. Now the HelloWorld.htm file is set as the default HTML page to run the Java applet.

10. Execute the project again. The selected browser will start and load HelloWorld.htm as the test page and load the HelloWorld.class Java applet.


NOTE: Just as in C/C++, names of functions, variables, and class files are case sensitive.

Using the Java Applet Wizard

Rather than creating a Java applet project from scratch, you can also use the Java Applet Wizard to generate a skeleton project. If you have worked with Visual C++ or Visual Basic, you are familiar with the concept of using wizards to automate the most common and mundane tasks associated with creating applications.

However, it should be noted that the wizard is only good for very simple applications. For complex applications, the wizard provides a good starting point, and then you can add your own code to modify the application to your own needs.

The Java Applet Wizard is a similar beast. It automates the task of getting started with creating a Java applet in Visual J++. The sample HelloWorld applet can also be created using the Applet Wizard. To use the Applet Wizard, complete the following steps:

1. Select New from the File menu to open the New dialog box.

2. From the Projects tab, select Java Applet Wizard and provide a name for your project, as shown in Figure 7.7.

FIG. 7.7
You can add the new project to the current workspace or create a new one.

3. Click OK. The Java Applet Wizard will begin, as shown in Figure 7.8.

4. Select the As an Applet Only option and provide a name for your applet; then click Next to continue.

5. Select the option for creating a sample HTML file and specify the applet width and height, as shown in Figure 7.9.

FIG. 7.8
The Java Applet Wizard can create an applet or an application.

FIG. 7.9
A sample HTML file can provide a convenient mechanism for testing your applet during development.

6. Click Next to continue. Step 3 of the wizard will be displayed, as shown in Figure 7.10.

FIG. 7.10
You can add sample event handlers for handling mouse events.

7. Select Yes to make the applet multithreaded. Select No, Thank You to disable animation options. Select all three event handlers to provide support for different mouse movements for the applet. A multithreaded applet can cede control to the system while it is loading and allows better performance in page loading and viewing.

8. Click Next to continue. The applet parameter screen will be displayed, as shown in Figure 7.11.

FIG. 7.11
You can always specify extra parameters and have the wizard create them.

9. Specify the following three applet parameters on the parameter screen:

Name Member Type Def-Value Description
captn m_captn string Hello World Text Caption
wdth m_wdth int 200 Applet Width
hgt m_hgt int 50 Applet Height

10. Click Next to continue. In the last step, enter the information you want the applet to return when queried for applet information. Enter the information as specified in Fig- ure 7.12.

11. Click Finish to continue. The wizard will display an information screen. Click OK and the wizard will create the necessary files and add them to your project.

12. Two files will be added to your project, the HelloWorld2.htm file and the HelloWorld2.java class file. You can now work with these files and customize your applet as you like.


NOTE: To add the HelloWorld applet code from before, just add the lines in the paint function to the paint function created by the wizard.

This section describes a simple Java applet but introduces you to some of the most common tasks involved in creating a Java applet. The process is fairly simple and straightforward, especially when using the Java Applet Wizard. The following section introduces you to the concept of using user interface elements, such as dialog boxes and menus, as part of your Java applet. In the next few sections, you will learn some of the more advanced techniques such as using resources and adding event handlers to your applets.

FIG. 7.12
The getAppInfo() method will return the information entered here to the querying application.

Adding Resources

Resources include such user interface elements as menus and dialogs. Under typical Windows development environments, most developers are very familiar with using resources such as menus, text boxes, lists, and so on. However, the Java language uses a different mechanism for handling resources. Java uses the Abstract Window Toolkit (AWT) to interpret source code to specify user interface elements, rather than using resource files and templates.

For that purpose, Visual J++ utilizes the Visual Studio resource editor to create resource files and templates and then uses the Resource Wizard to convert these resource files into Java classes. The following sections describe creating resource files for your Java projects and then converting them to Java classes using the Resource Wizard.

Creating Resources

Resources are created using the menu and dialog editors included with Visual Studio. Resources can be created from scratch, or you can import resources from other projects by using the Visual Studio file drag-and-drop capabilities. To create a resource template file for your Visual J++ project, open the project and then complete the following steps:

1. Select New from the File menu.

2. On the Files tab, select Resource Template and provide a name for the template, as shown in Figure 7.13.

FIG. 7.13
Resource Template is a special folder that holds all your resource files in a project.

3. Click OK. A HelloWorld.rct file will be added to the project.

4. Double-click the file and the source editor will open the resource template folder with an empty resource folder.

5. To add a resource to the template, select Resource from the Insert menu. The Insert Resource dialog box appears, as shown in Figure 7.14.

FIG. 7.14
Valid resource types for all Visual Studio 97 products are listed in the Insert Resource dialog box.

6. Select Dialog from the list and click New. A new dialog will be added, and the dialog editor will start, as shown in Figure 7.15.

FIG. 7.15
A default dialog with an OK and a Close button is added by the Insert Resource dialog box.

7. Double-click the dialog box to open the Dialog Properties dialog box, as shown in Fig- ure 7.16.

FIG. 7.16
The Dialog Properties box can be used to specify various properties such as caption and font style.

8. Change the ID and the caption of the dialog box to an appropriate name and caption for your dialog box.

9. Add controls to the dialog box by dragging controls from the Controls Toolbox palette to the dialog resource.

10. Close the dialog editor by clicking the Close icon and save your changes.

You have just created a resource template for your project with a dialog resource. You can now convert your resource template to a Java class file by using the Resource Wizard. However, the Java language only supports a subset of Windows resources. Any resource used in a resource template that does not have a Java counterpart is ignored during the creation of the Java resource class.


NOTE: Although the Dialog editor allows you to place all the controls in the Controls toolbox on your dialog template, only those supported by the Resource Wizard will be converted to Java GUI components by the Resource Wizard.

The following resource types are supported by the Java AWT:

Running the Resource Wizard

The Resource Wizard converts the templates and resource files created by the resource editor into Java class files. To convert a resource template using the wizard, take the following steps:

1. Select _Java Resource Wizard from the Tools menu.

2. The wizard will start, as shown in Figure 7.17.

FIG. 7.17
The wizard can convert either resource template files (.rct) or compiled resource files (.res).

3. Provide a filename or select Browse to select a file from an open dialog box.

4. Click Next to continue. The resources available for conversion will be displayed, as shown in Figure 7.18.

FIG. 7.18
Only dialog and menu resources are listed in the listbox.

5. Select the resources to convert and click Finish.

6. The wizard will list the files that will be created. Click OK.

7. The files will be created and placed in the project root directory. You can add the files to the project now by using file drag-and-drop techniques.

Using the Resource Wizard Generated Files

Once you have created the Java class files for the resources and added them to your project, you can use the resources in these files as a part of your Java applet. To use the Java dialog class in your project, complete the following steps:

1. Open the Java applet file, HelloWorld.java, and add the following code to the beginning of the file:
import java.awt.*;
import java.applet.*;
import MyDialog;
2. In the applet class declaration, add the following line:
MyDialog dlg;
3. Add an init() method to your applet, as shown in the following:
public void init() 
{
dlg = new MyDialog(this);
dlg.CreateControls();
}
4. Comment out the call to the drawString method in the paint function.

5. Now add the following code at the end of the applet class declaration. This code toggles the button text when the button is clicked:
public boolean action(Event evt, Object arg)
{    
     if(evt.target instanceof Button)
     {   
     String str = dlg.IDC_TEXT1.getText();
          if (str == "Hello World")
          {
               dlg.IDC_TEXT1.setText("Hello Java World");
          }
          else
          {
               dlg.IDC_TEXT1.setText("Hello World");
          }
               return true;
     }
     return false;
}
6. Save the file. Select Execute from the Build menu to run the applet.

7. An applet will be displayed with a single button that you can click to change its label from OK to Clicked! and back.

Adding Event Handling

The action function, defined in the preceding section, is an event handler that is called every time the controls on the applet generate an event. Take a look at that function again:

public boolean action(Event evt, Object arg)
{    
     if(evt.target instanceof Button)
     {   
String str = dlg.IDC_TEXT1.getText();
          if (str == "Hello World")
          {
               dlg.IDC_TEXT1.setText("Hello Java World");
          }
          else
          {
               dlg.IDC_TEXT1.setText("Hello World");
          }
               return true;
     }
     return false;
}

The action function checks to see if a button generated the event. If there were more than one button on the dialog, you would need to determine which one generated the event. In this case, there is only one button, so you can be sure that it generated the event. The function then checks the value of the button label and toggles it appropriately.

The Java specification includes an Event class for providing event handlers for events such as mouseUp, mouseDown, and so on. The component class included with the Java language specification provides support for handling events. You can override the events provided with the component class by writing your own event handlers for the events handled in the component class.

Debugging Your Applets

Debugging is the process of finding errors and mistakes in your application code. Visual J++ includes an integrated debugger that simplifies the task of finding errors in your applications and correcting them.

Before you can debug your application in Visual J++, you must set up the project and the environment for debugging. Visual J++ uses different methods for debugging applications and applets. When you are debugging an application, your program runs in a standalone interpreter; when you're debugging an applet, your program runs in a browser.

To set up the environment to debug a Java application, complete the following steps:

1. Select Settings from the Projects menu. The Project Settings dialog box appears.

2. Select the Debug tab, as shown in Figure 7.19.

FIG. 7.19
The Project Settings dialog box provides a one-place setup of all environment options for a Visual J++ project.

3. In the Class for Debugging/Executing text box, type the name of the class that contains the application's main() method.


NOTE: A Java application must contain a main() method. It is the function the Java virtual machine uses to start the application.
4. Click the Stand-alone Interpreter option.

5. Click OK. You are now ready to debug your application.

To set up the environment to debug a Java applet, follow the same procedure, but in step 3, provide the name of the applet's init() class instead.


NOTE: A Java applet does not need a main() method. However, applets do include the init() method, which is the function first called when an applet is starting.

Once you have set up the project environment for debugging, you can use the debugger to control the execution of your program by setting breakpoints and examining the status of your applet. The debugger also provides support for debugging multithreaded programs.

The most common kinds of errors encountered by developers are the syntax errors that prevent a program from being compiled. The Output window displays errors that prevent a program from being built and provides the filename, line number, and error number. The Output window behaves like a source window; you can copy and print information from the window. If the status bar is displayed, it gives a summary of the current error.


TIP: You can get help on any error by moving the insertion point to the error number and pressing the F1 key. The online help information will be displayed.

To fix a compile-time error, simply double-click the error line in the Output window, and the source editor will open the appropriate file and place the cursor at the line where the error happened.

The exception-handling facility in Java allows programs to handle abnormal and unexpected situations in an orderly, structured manner. When a method detects an exception that must be handled, it notifies the exception handler using the throw method. The exception handler receives the notification using the catch method. For a more detailed discussion of these methods and of Java in general, check out these books:

If no catch handler exists for an exception, the program typically causes the Java interpreter to print an error message, print a stack trace, and exit. If you are debugging a program in Visual J++, however, the debugger notifies you that the exception was not caught.


NOTE: Developers familiar with the C++ exception-handling mechanisms will immediately recognize the throw and catch methods used by Visual J++ as a comparable mechanism.

From Here...

In this chapter, you learned about creating Java applets and applications using the Visual J++ development environment. You learned about creating projects to build Java applets, about building and testing your applets using the integrated environment and web browsers, and about using the integrated debugging capabilities of the Developer Studio 97 IDE. In addition, you learned about using the wizards provided with Visual J++ for getting a jump start on your development efforts.


Previous chapterNext chapterContents


© Copyright, Macmillan Computer Publishing. All rights reserved.