- Special Edition Using Java, 2nd Edition -

Chapter 53

Borland C++ 5.0


by Raghuram Bala with Joe Weber

This chapter focuses on building Java applications using the Borland IDE and is not intended to be a Java language tutorial. Readers interested in learning more about the syntax and architecture of the language can refer to Java By Example from Que Corporation.

The Borland C++ Java Environment

Borland C++ 5 has included support for Java application development using the Borland C++ Add-On Environment for Java (BCAJ). Using BCAJ, you can write, compile, view, and debug Java applications and applets from within the Borland IDE.

BCAJ includes the following components that speed up Java applications:

The sample programs written in this chapter were tested under Windows NT and Windows 95.
 

Installing Borland C++ Add-On Environment for Java

The BCAJ can be installed from the initial setup window by clicking the BCAJ check box. If you have already installed Borland C++ 5 and need to install BCAJ, then perform the following steps:

Go the \BC5\BIN directory using either File Manager or Explorer (for Windows 95).

Run ADDONREG.EXE. Select New Entry, choose the BCWJAVA.DLL, and click OK. This makes an entry for BCAJ in the registry.

Run the self-extracting executable, BC5\JAVA\SRC.ZIP. This installs the required Java class libraries, sample applications, and tools.

Add the environment variable Classpath=C:\Bc5\Java\Classes. In Windows NT, you can change the environment variables by double-clicking the System icon in the Control Panel. In Windows 95, you can change the environment variables by modifying the AUTOEXEC.BAT file.

Reboot your machine to reinitialize the environment variables.

Start Borland C++ to load all of the components that make up the BCAJ.

The Borland IDE

The JDK, released by Sun Microsystems, was a set of tools without an integrated development environment. Although Java is a relatively easy-to-use language, it was cumbersome to construct large applications and keep track of projects. With the Borland IDE, the task of managing projects, compiling, and debugging becomes much easier with a GUI that allows developers to focus on the project at hand.

Before starting your first Java project, you may want to set up your Borland IDE so that it is more suitable for Java development. Choose Options, Environment, Customize. Next, from the Available Buttons list box, select the entry called Syntax Highlight Java Files and move it to the Active Buttons list box by clicking the right arrow, as seen in figure 53.1.


FIG. 53.1

Adding the Java syntax highlighting to the IDE.

This enables the Borland IDE to highlight the Java syntax when editing .java files. Notice an additional button on your toolbar.

If you have already added the C++ syntax checking option, then you can switch between Java syntax checking and C++ syntax checking by clicking the appropriate toolbar button.

One of the main uses of Java is for developing Internet applications. This requires Java programs to be coded as Java applets and embedded in HTML files. To test Java applets, I recommend associating a Web browser with the Borland IDE. For example, if you want to associate the Netscape Navigator Web browser, choose Options, Tools, and click the N ew button. This brings up the dialog box shown in figure 53.2.


FIG. 53.2

Associating Netscape with the Borland IDE.

The Command Line text box has a suffix, file:///, that may vary from browser to browser. For example, in the HotJava browser the suffix is docs:///. The variable EDNAME is an internal Borland variable that is set to the name of the currently active file in a project.
 

Click the Advanced button as shown in figure 53.3 to set up advanced configuration options for the Netscape browser.


FIG. 53.3

Associating HTML files with Netscape in the Borland IDE.

Figure 53.4 shows a dialog box with advanced configuration options for setting up the Netscape browser.


FIG. 53.4

Advanced configuration options for the Netscape Web browser.

Notice that the Viewer option is set to .html:, which indicates that Netscape is now one of the viewers capable of handling HTML files. The Default For field indicates the files types for which Netscape is the default viewer or editor. I have left it blank so that the default viewer for HTML files is a text editor. This means that you can use the Netscape Web browser in addition to the text editor to view or edit HTML files.

With Netscape setup, you can select Netscape as a viewer for HTML files where appropriate. You learn about this later in the section "Running a Java Applet."

Creating a Java Project

Now you are ready to embark on your first Java project! To create a project, choose File, New, Project, and the New Target dialog box appears. Select Java class as your Target Type and set up the Project Path and Name as shown in figure 53.5.


FIG. 53.5

Creating a Java project.

Notice that the Launch AppExpert for Java check box is unselected. This has been done intentionally as you first explore the steps in creating a Java program without the AppExpert. You tackle the AppExpert later in the section "Using AppExpert." Click the OK button to create the project.

Once the project is created, the Borland IDE creates three files (nodes) as shown in figure 53.6.


FIG. 53.6

Nodes created by the Borland IDE.

In our first project, you will attempt to write a simple Java program that draws a rectangle between two Cartesian coordinates, (x1,y1) and (x2,y2). The rectangle is drawn with a blue frame and filled with yellow using the Java Graphics library.

To enter the code for the project, double-click the Rectangle.java node, or right-click the mouse button and use the SpeedMenu (see fig. 53.7).


FIG. 53.7

Editing a Java program.

Listing 53.1 shows the code for the Rectangle application.

Listing 53.1 Lstb_1.txt—A simple rectangle program.

// Author: Rahi Racharla
// Creates color filled rectangle for every two mouse clicks.
// calculates the height, width of the rectangle using Math class
1. import java.applet.*;
2. import java.awt.*;
3. public class rectangle extends Applet
4. {
5. int x1, y1, x2,y2,flag;
7. public void init()
8. {
9. resize(300,500);
10. }
11. public void paint(Graphics g)
12. {
13. int a,b,c,d;
14. a = Math.min(x1,x2);
15. b = Math.min(y1,y2);
16. c = Math.abs(x1-x2);
17. d = Math.abs(y1-y2);
18. g.setColor(Color.blue);
19. g.drawRect(a,b,c,d);
20. g.setColor(Color.yellow);
21. g.fillRect(a+2,b+2,c-2,d-2);
22. }
23. public boolean mouseUp (Event evt, int x, int y)
24. {
25. if (flag==0)
26. {
27. x1 = x;
28. y1 = y;
29. flag = 1;
30. }
31. else
32. {
33. x2 = x;
34. y2 = y;
35. flag = 0;
36. repaint();
37. }
38. return true;
39. }
40. }

In the Rectangle application, the init function overrides the init function of the Applet class and creates a canvas for the Java applet, which has a size of 300 [ts] 500. Next, it stores the coordinates for the rectangle using the coordinates of the mouse when the user clicks the mouse. When two consecutive mouse clicks are recorded, the repaint function is called. The repaint function causes the rectangle to be drawn and filled. Prior to drawing the rectangle, you use the Math class supplied by the BCAJ and its abs and min functions to correctly determine the top-left coordinates, the width, and height for the rectangle.

When you are using Netscape, an applet can only be resized to the size specified in the HTML. The resize statement here will only help you when using Appletviewer.
 

Setting Up Runtime, Compiler, and Debugger Options

Before compiling your rectangle application, you need to set up the Project options. Choose O ptions, Project to bring up the Project Options dialog box (see fig. 53.8). Highlight the Java topic and observe the entries to the right of the dialog box.

The CLASSPATH field is important. Note that you entered a CLASSPATH environment variable when you installed the BCAJ, which set up the default path for all system-wide Java classes. Now, if you had additional user-defined Java classes, then you could specify them here.

The Output Class Base Directory field is where the resulting compiled Java bytecodes are stored. The output files have a .class extension.

The Class Runtime Arguments field can contain any options mentioned in table 53.1. Finally, the AppAccelerator check box is checked by default. The AppAccelerator is Borland's just-in-time compiler for Java that enables applications to run 10 times faster when compared with the interpreted-mode Java.


FIG. 53.8

Setting the Java project options.

Java Runtime options are listed in table 53.1.

Table 53.1 Java Runtime Options

Runtime Option Description
-cs Checks the source if it is up to date before running. If the source is out of date, it recompiles the class.
-ms x Sets the memory allocation pool to x bytes. Default 3M, minimum 1K.
-noasyncgc Switches off asynchronous garbage collection.
-noverify Switches off bytecode verification.
-oss x Sets the maximum stack size for a Java thread to x bytes.
-prof Creates a profile file for use with Java Profiler.
-ss x Sets the maximum stack size for a 'C' thread to x bytes. Minimum 1K.
-v Displays a message on Stdout whenever a class is loaded.
-verbosegc Prints a message when garbage collector frees memory
-verify Switches on bytecode verification.
-verifyremote Switches on bytecode verification for remote classes loaded using Class Loader.

You can set various Compiler options with BCAJ in the Project Options dialog box under the Java topic as seen in figure 53.9. The Compiler options are listed in table 53.2.


FIG. 53.9

Setting Java Compiler options.

Table 53.2 Java Compiler Options

Compiler Option Description
No Warnings Suppresses compiler warnings.
Optimize Optimizes the compiled code by inlining static, private and final methods.
Verbose Displays messages about source files being compiled and classes being loaded.
Depend N.A.
Nowrite N.A.
Generate Debug Info Switches on/off creation of debugging information for use by Java Debugger.

You can also set up Debugger options used with BCAJ in the Project Options dialog box under the Java topic as seen in figure 53.10. You would fill the Source Path field with the path to the Java classes that you want to debug.


FIG. 53.10

Setting Java Debugger options.

Compiling a Project

Now that you have set up the various Java Runtime, Compiler, and Debugger options, you are ready to compile the program. To compile a single Java file, highlight the Java file and right-click the right-mouse button to pull up the SpeedMenu, and select JavaCompile (see fig. 53.11).


FIG. 53.11

Compiling a single Java file.

If your project consists of more than one Java file, choose Project, Build All.

After compilation, a status window appears and indicates if the compilation ran successfully, as shown in figure 53.12.


FIG. 53.12

Compilation status window.

To intentionally generate a few errors, I have introduced a small typographical error from the code listed in listing 53.1. I removed the semicolon at the end of line 14. These error messages can be viewed by choosing View, Message as shown in figure 53.13. Although the error is a simple typographical one, notice that it leads to several other error messages to be generated.


Fig. 53.13

View message window showing compilation errors.

An exclamation mark "!" in the left margin indicates an error message; the line immediately following the exclamation point is the line of code that contains the error.

Debugging a Project

After having successfully compiled the Java program, you can run your Java program. However, I have altered listing 53.1 yet again by introducing a logical error in line 15, which now reads b = min(x1,x2);.

This code passes through the compiler successfully but does not provide the desired effect of drawing the rectangle properly between the first and second Cartesian coordinates.

To invoke the Java Debugger, select the class file, and display the SpeedMenu by right-mouse clicking. Next, choose View, Debug Java Code shown in figure 53.14.

To run the Java Debugger, you must set the Compiler options to Generate Debug Information. Once debugging is complete, you should recompile the program with the G enerate Debug Information check box turned off because it creates additional overhead.
 


FIG. 53.14

Invoke the Java Debugger.

The Java Debugger has five panels (shown in fig. 53.15):

Panel Description
Code Contains the source code.
Message Displays messages about the state of your applet as you run and debug it.
Stack Shows the methods yet to be run when you come to a breakpoint.
Current Context Displays information about objects and their attributes when debugging a more complex applet.
Watch Shows the values of variables that you have selected to keep track of.

To set a breakpoint, go to the appropriate line in the Code panel and click the left margin of a line with executable code. For example, you cannot set a breakpoint on a comment line.


FIG. 53.15

Setting a breakpoint.

The sample programs written in this chapter were tested under Windows NT.
 

Breakpoints are indicated by a small red dot appearing on the left margin of the line where the breakpoint is set. You can clear a breakpoint by clicking the left margin.

To watch variables, the Current Context panel displays variables that are in scope. So, if you want to watch specific values, select the variables from the Current Context Panel, which is organized as a hierarchical series of folders. After highlighting the variable in question, you can add it to the Watch panel by choosing Debug, Add Watch.

Conversely, you can remove a variable from the Watch panel by highlighting it and choosing D ebug, Remove Watch.

Choose Debug, Run to execute the code. The execution pauses when it hits a breakpoint. At this stage, you have three options:

When a running a Java program that takes parameters, the parameter values appear in the Current Context panel. You view them just like any other variable.

Running a Java Program

To run a Java program, you can either run it as a standalone application using the Java View in the Borland IDE, or as an applet by creating a HTML page and invoking a Java-enabled Web browser.

Running a Standalone Java Program

To run a standalone Java program, select the .class file in the project and choose View, Java View from the SpeedMenu. This invokes a viewer program called Java View, which provides an environment to execute the program (see fig. 53.16).


FIG. 53.16

Invoking Java View.

The Java View window appears as shown in figure 53.17, and you can execute your application within that environment.


FIG. 53.17

Running a standalone Java program.

Running a Java Applet

To run a Java applet in a browser, you need to create a HTML document that has references made to the applet in question. You use the <applet> and </applet> tags to accomplish this.

The HTML document can be created in a number of ways. One method is to select the HTML file within the project and choose View, Text Edit from the SpeedMenu. This puts you into a blank file where you enter the code in the listing 53.2, which shows a HTML document with an embedded call to the Rectangle applet.

Listing 53.2 Lstb_2.txt—HTML Document-calling Rectangle applet.

<title>The Rectangle Applet</title>
<hr>
<applet code=rectangle.class width=300 height=500>
</applet>
<hr>

After having saved the HTML document, you can invoke the Web browser (for example, Netscape) you configured earlier to work with your HTML files.

Figure 53.18 shows the Java applet running on the Netscape Navigator 2.0 Web browser.


FIG. 53.18

Running a Java applet in a Web browser.

Using AppExpert

What you have done thus far is to create a Java application by hand. BCAJ comes with a AppExpert tool that simplifies some of the steps in creating a Java application. AppExpert generates skeleton code depending on options you select.

When you create a new Java project, ensure that the Launch AppExpert for Java check box is checked as seen in figure 53.19.


FIG. 53.19

Generating AppExpert skeleton code.

AppExpert generates three nodes as seen earlier in figure 53.5. The Borland AppExpert for Java is launched at this time, as shown in figure 53.20.


FIG. 53.20

AppExpert window.

The AppExpert tool is a wizard-like tool that allows you to develop Java applications quickly by providing a few user-configurable settings such as the tabs:

Once these user configurable values are entered, AppExpert generates skeleton code (shown in fig. 53.21) that can be viewed by selecting the Code Preview tab (refer to fig. 53.20).


FIG. 53.21

Code preview in the AppExpert window.

To save the code generated by AppExpert, do not forget to click the Save button on the AppExpert toolbar.
 

Listing 53.3 shows the source code generated by AppExpert.

Listing 53.3 simpledraw.java—Code generated by AppExpert.

//------------------------------------------------------------------------------
// simpledraw Simple Draw Java Program
// Copyright 1996, All rights reserved
// QUE Publishing
// Version: 1.0
// Author: Rahi, R
// Created: 3/3/96
//------------------------------------------------------------------------------
import java.applet.Applet;
import java.awt.*;
import java.awt.*;
public class simpledraw extends Applet implements Runnable
{
// Variables for thread guards
Thread thread = null;
int count = 0;
// Class initialization code
public void init()
{
startThread();
}
void startThread()
{
if (thread == null)
{
// Start another thread on this object);
thread = new Thread(this);
// Will ultimately cause a separate thread to call the run method
thread.start();
}
}
void stopThread()
{
if (thread != null)
{
thread.stop();
thread = null;
}
}
// Mouse button pressed handling code
public boolean mouseDown(Event event, int x, int y)
{
// Insert your mouse code here;
return false; // because we didn't handle the event
}
// This routine handles the painting
public void paint(Graphics graphic)
{
// Insert your paint code here;
}
// Implements Runnable Interface
public void run()
{
// This method is called when a new thread is started (care of Runnable interface)
// This is a waste of CPU resources
while (true)
{
try
Thread.sleep(1000);
catch (InterruptedException e)
;
repaint();
}
}
// For running standalone
public static void main(String[] argv)
{
// Create the frame and launch simpledraw
Frame f = new Frame("simpledrawFrame");
f.reshape(100, 100, 200, 100);
f.show();
simpledraw x = new simpledraw();
f.add("Center", x);
x.init();
x.start();
}
// Constructor
public simpledraw()
{
}
} // end class simpledraw

By using this code framework as a starting point, you can build feature-rich Java applications.


Previous Page TOC Next Page

| Previous Chapter | Next Chapter |

|Table of Contents | Book Home Page |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company