- Using Visual J++ -

Chapter 9

Overview of Java Code


In this chapter, you will write your first Java applet, from scratch, without using the Visual J++ Java Application Wizard to generate the initial skeleton program. In doing creating an applet from scratch, you will learn how to build simple applets and you'll begin to learn some of the Java language specifics as well.

Java is not a difficult language to learn. In fact, much of the skills of Java programming come from knowing which internal pre-built procedures to run. For example, when you want to print a message in color, you don't have to do much more than find the name of the pre-built procedure that first sets the color, find the name of the pre-built procedure that prints on the applet window, and then type those procedures into your Java applet code.

Once you finish this chapter, many terms that were probably new to you when you started this book will begin to make more sense. For example, you'll better understand the terms method and object-oriented programming. When you finish this chapter, you will completely understand how a Java program works and how it prints a message in color. You will even know enough to modify that program somewhat. You will then be able to change the message, add an additional message, or select another color. Any changes you make will only strengthen your Java and Visual J++ skill set.

In this chapter, you'll learn about the following:

The Nature of Java Programs

A Java program is typically small. Java's size allows programmers to use Java in computers that don't have a lot of computing power. For example when Sun developed Java, Sun foresaw that their new language might be used in places where embedded code controls activities such as in automobiles and phones. As such, they kept the language small and the associated library files small as well.

A small size does not always translate to an easy language to understand. For instance, QBasic, one of the best learning languages for beginning programmers, has almost 4 times as many commands as the C language, yet, C is much more difficult for the novice programmer to learn. Java, however, seems to be a good middle-ground language because newcomers can learn to write simple applets without a lot of programming background.

You already saw in chapters 6, "Reviewing the Sample Code," and 7, "Reviewing Java's Nature," how one can take advantage of Java code that someone else wrote and extend that code to make the programs behave differently. This extension is one of the fundamental advantages to object-oriented programming (or OOP as it's called). An OOP language, such as Java or C++, treats data items as objects that the code operates upon. Instead of focusing on commands, the language focuses on the data itself. When you extend one program, you inherit data and data behaviors from the existing code.

You'll feel much more comfortable about Java once you finish this chapter because you'll see what all the fuss in chapter 7 was all about. Instead of entering cryptic code that changes the behavior of a pre-written program, you'll write your own program from scratch. In doing that, you'll understand that chapter 7 worked extensively with object-oriented programming to demonstrate the extensible nature of Java code. In addition to filling in parameter values at runtime, you will learn how to extend a program through inheritance to take advantage of even more powerful code already written.

How C++-Like Is Java?

C++ programmers will look at Java programs and immediately see the similarities between the two languages. Much of a Java program translates verbatim to the C++ language, including a majority of the syntax, looping constructs, and data definitions. You learned in chapter 4, "Using the Visual J++ Wizards," that the Java comments are identical to C++'s (and some are compatible to C also).
 
Java does differ in some ways from C++. When Sun developed Java, Sun wanted a C++-like language that was easier to master and harder to mess up.
Java supports strong type checking. That is, a Java compiler closely checks your data for accuracy during the compilation, whereas C++ is less prone to data checking. Therefore, runtime errors often occur when you run C++ programs that would otherwise be caught by the compiler if C++ were more strongly type-checked. (C++ is more strongly type-checked than C, though.) Java even supports a string data type, a welcome relief to C++ programmers turning to Java.
 
People moving from other programming languages to C++ are often frustrated by C++'s lack of true array capabilities. (C++ programmers must use pointers to simulate array manipulation.) Thankfully, Java supports true array data types, including arrays of strings. Java will not let you work with pointers directly so you cannot access data areas you don't have security clearance to and neither will you be prone to program crashes.
 
Java does not directly support multiple inheritance (many C++ programmers don't use multiple inheritance anyway due to its potential side effects). There are no Java struct or union data types. Perhaps most surprisingly, Java does not support dynamic memory allocation and deallocation. Despite these language differences, the C++ programmer certainly has an advantage of familiarity when moving to the Java language.

By looking at an extremely simple Java program, you can familiarize yourself with the nature of all Java programs. Listing 9.1 contains an extremely simple Java program that you can enter and run from Visual J++.

So simple is listing 9.1's program that such a simple program is almost more difficult to set up in Visual J++ than a complex program because the application wizard generates so much for you when you need more extensive code. For an extremely simple, minimal program such as the one in listing 9.1, you'll see that you have to jump through hoops to enter and execute the code. The effort is useful, however, because you should begin analyzing Java code by looking at the simplest possible program before moving to more comprehensive programs.

To try this example, don't use the wizard to generate a project. Instead, perform these steps to enter the program in a project workspace:

  1. Close your current Visual J++ workspace if you have an open project showing.
  2. Choose File, New to display the New dialog box.
  3. Select Project Workspace to open a new project. (All Java applets must reside in a project.)
  4. Select the Java Workspace option from the Type option list because if you select Java Applet Wizard, Visual J++ will run the wizard and generate a much more complex project than you need.
  5. Type the name Simple in the Name text box.
  6. Click the Create button to create the empty project named Simple.
  7. Choose Insert, New Java Class to display the Create New Class dialog box (see figure 9.1).


FIG. 9.1

You must insert a new class for this program.

  1. Type Simple in the class Name text box, and type Applet in the Extends text box.
  2. Mark the Public check box.
  3. 10. Click OK to add the class to the project and open the code window. The new class contains the same name as the Java program, as is always the case. You had to tell Visual J++ about the new class by inserting the class because the source code alone is not enough to inform Visual J++ of the class. Again, the wizard does all this for you automatically for you and you generally will not have to perform these tedious steps for other applets.
  4. 11. Finally, modify the source file that Visual J++ displays in the Editing window to match listing 9.1. This will give you good practice with the editor. Remember to enlarge the Editing window if you need more editing room.
  5. 12. Choose Build, Execute to see the applet. Visual J++ will create a default HTML file for you and run the applet with your Web browser. You could also use your JView applet viewer (see chapter 5, "Running Visual J++ Programs") to see the applet instead of viewing the applet with your Web browser. You will have to type the class name Simple so tha Visual J++ knows the class to use with the applet, and also you should let Visual J++ know if you're running the applet under a Web browser or the JView applet viewer by selecting the appropriate option.


listing 9.1 A Simple Applet

//*******************************************************************
// Simple.java: Applet
//*******************************************************************
import java.applet.*; // Requires support files
import java.awt.*;
//===================================================================
// Main Class for Simple applet
//===================================================================
public class Simple extends Applet
{
public void init()
{
resize(320, 240); // applet's window size
}
//--------------------------------------------------------------
public void paint(Graphics g)
{
// Change subsequent text color to red
g.setColor(Color.red);
// Write a simple message in the window
g.drawString("Very simple!", 75, 100);
}
}

 
Can you see how indention and whitespace can make your programs more readable? By indenting one tab stop for each enclosed set of grouped statements, you can easily spot where one group begins and ends. You can also tell how some groups of statements fall within other groups. Compare listing 9.1 with the terrible listing 9.2. Both are identical and both do the same thing without any errors. Which code would you rather have to change later? Obviously, if you indent regularly and use ample whitespace and separating comment lines, you'll make your programs more readable and you'll be able to update your programs more easily in the future when you must make changes to them.


Listing 9.2 You Can See Why Ample White Space, Comment Separation, and Indention Is a Good Thing

// Simple.java: Applet
import java.applet.*;// Requires support files
import java.awt.*;
// Main Class for Simple applet
public class Simple extends Applet
{public void init(){resize(320, 240);// applet's window size
}public void paint(Graphics g){// Change subsequent text color to red
g.setColor(Color.red);// Write a simple message in the window
g.drawString("Very simple!", 75, 100);}}

Figure 9.2 shows the result of running the applet in the default Internet Explorer HTML page that Visual J++ automatically creates when you select Build, Execute.


FIG. 9.2

A simple applet that displays a red message.

Program Format

Here are few points to notice about listing 9.1's sample applet:

Import java.awt.*;

import java.awt.*;

These general coding principles apply to small as well as large Java programs. When you first begin writing Java programs, you may forget some of these coding conventions. Visual J++ lets you know what you did wrong, however, because if you violate one of these conventions, you will almost always trigger a syntax error that Visual J++ will catch during your project's compilation.

In the next chapter, you'll learn all about the details of the Java language. For now, you'll get a good overview by analyzing each of the Simple.java program's lines. The following sections explain the parts of the Simple.java program that you just entered.

Extended Comments

The following lines appear at the top of the Simple program:


//***********************************************************************
// Simple.java: Applet
//***********************************************************************

You already know what these lines do. Actually, these lines do not do anything because they are comments. The comments describe the program to whomever looks at the program. Comments do not execute but are there for informational purposes only. These comments contain wrapper comment lines. The first and last comment, containing a row of asterisks, simply provide wrappers for the middle, informational comment that holds the program name. The asterisk lines are good comments to scatter throughout your code to separate parts of the program from each other. As you can see from listing 9.1, you can use the hyphen and equal sign to separate lines as well.

Although the principle is not fixed in stone, you might want to follow the wizard's generated comment style described in table 9.1.

Table 9.1 The Wizard's Commenting Style for Line Separators

A Line of These Separates This...
Asterisks A section with information comments about the program such as the program name and programmer
Equal signs A class description
Hyphens A class procedure definition
 
A great use for initial comments is the program source code name, project name, programmer name, and the date that you last modified the program and a description of the modification that you made. You might also put a high-level description of the program at the top of the code as well. Later, when you or someone else has to make changes to the program, you'll know who last worked on the program and what they did.

Scatter comments throughout a program to describe, in human terms, what the program is doing. For example, the following line is cryptic:

for (i=1; i<totNum; i++)

If, however, you preceded the line with the following comment, you'll know right away what the line is supposed to do the next time you need to analyze the program and make changes to the program.

// Step through all the client records

Explaining import

These next two lines in the Simple program appear in almost every Visual J++-based Java program you'll write:


import java.applet.*; // Required support files
import java.awt.*;

 
If you know C or C++, the import command is analogous to the #include pre-processor directive. Unlike #include, however, import is a Java command; hence, the required semicolon after the command.

The import command inserts classes from other class packages into your program. Remember that a class is a collection of data and routines that you use or write. A package is a collection of classes that are logically grouped together. For example, Visual J++'s pre-installed threading classes all appear inside a single class package.

Instead of writing your own graphics routines when you want to draw a box, you can take advantage of the graphics routines supplied with Visual J++ in the graphics class.

The import command often follows two formats:

import specificPackage.specificClass;

import specificPackage.*;

When you know the exact name of a class that you want to use, you can specify that name inside the import command. The specificPackage is the name of the class package from which you want to import the class named specificClass.

All this talk about classes might confuse you at this point. After all, the Java program that you write is a class, you use procedures, or methods, from classes within your program, and you import classes from other locations, such as from the Visual J++ internal class library packages as done in the Simple.java applet. The classes contain all code executed in Java. When you write a program, you are, in effect, adding a class to the collection of classes already on your machine. Your program is an addition to the other classes that you and your co-workers might write, as well as to the supplied classes that Visual J++ provides. you can get classes from other sources as well.

As you can see, all work is done from inside classes and classes can share power from other classes. Therefore, when your program, a new class, needs to print something on the screen, you should use one of the routines from an output class supplied by Visual J++. You could write your own output routine from scratch, but the goal of the pre-defined class packages is to make your programming life easier and quicker so you have more room for those exotic Jakarta holidays. (Jakarta is the capital of the country named Java, by the way.)

The second form of import uses a wildcard asterisk to specify that you want to import all classes from a class package. The Simple.java applet uses this import form for its own imported classes. The Java.applet class package is a necessary class for you to use to embed your own Java applet on Web pages. Therefore, you'll always import java.applet and all its classes at the top of every applet that you write (so does the Visual J++ wizard).

The java.awt class package contains lots of graphics routines that let you send output to a Web page applet window. If you're used to programming in text-mode environments, such as MS-DOS, you must re-gear and get used to working in a graphics environment. Instead of printing text on the screen, you often draw text. The Simple.java program contains a reference in the body of the code to drawString() (the parentheses indicate that drawString is a method which is a class procedure) and the instructions for drawString() appear in the java.awt class package.

Table 9.2 contains a description of common class packages.

Table 9.2 Common Class Packages You Can Use in Your Java Programs

Package Name Description
java.applet The parental applet class that contains all the information and methods you need to embed an applet inside a Web page.
java.awt Contains graphics-related methods.
java.io Contains methods that perform input and output.
java.lang Contains system interface information that your applet will need. Java automatically imports this class package for you so you'll never import the class package yourself.
java.net Holds networking environment support.
java.util Contains several utilities for data structure storage, such as linked lists and data manipulation.

Locating Classes

One concern that all newcomers to Java programming face is knowing which class packages are available and learning how to use them. The chicken-before-the-egg paradox appears here because if you were a given a list of every class method name, how would you know when to use the methods and how would you know exactly what each one did? If you were given a list of classes, methods, and detailed descriptions, you would face information overload because you might never use many of the methods and some of the methods are dual-purpose and overlap in functionality.
 
Therefore, this book will mention classes and methods that you can use as they arise in the discussion. Generally, there are methods that handle just about any input or output that you'll perform, methods that perform mathematical calculations, methods that manipulate strings, methods that access other Web locations, and methods that do just about any other task that an applet might be required to do.
 
Once you make your way through this book, chapter 19, "Visual J++ Applet and AWT Class References," reviews several of the more common and useful methods and class packages that you'll be able to use with Visual J++. The nice thing about Visual J++ is that Microsoft decided to use the standard class packages from the Sun de facto industry standard, as well as supply some new features as well. By the time you finish this book, you will have seen several of the pre-built methods in use as well as understand chapter 19's reference to the other classes that are available to you as a Visual J++ programmer.
 
By the way, if you've written Windows programs in C or C++, or used the Windows API from within another language such as Visual Basic, you'll find that many of the Windows-based methods are similar to those you have used before.

Extending Your Applet

After a comment, you'll see the following two lines:


public class Simple extends Applet
{

The opening brace begins a group of statements that make up the body of your program's class named Simple. The class does not terminate until the last line of the program which closes out the braces and the grouped statements between the braces.

Although this public class statement looks fairly complex, the statement is required for your applets. The statement informs Visual J++ that you want to create your own class. To create the class, you subclass another class called the Applet class. Subclassing refers to the practice of taking an existing class and making a copy of it in addition to extending that new class's capabilities. In this example, you are taking the generic class called Applet, that comes pre-built into the java.applet class package, making a new copy of the Applet class, naming the copy Simple, and adding your own functionality to it.

If you were to have to write the Applet class from scratch, your programs would be huge and your Java tutorial would take much more time than necessary. As you've already seen in the second part of this book, of the advantages of Java, and of most OOP languages, is that you can inherit functionality from code that's already written. The Applet class contains all the code needed to write on a Web page. You want your applet to write on a Web page also, so why not borrow the code from the java.applet class package Microsoft gave you with Visual J++?

Therefore, the statement creates a new class using the functionality of the Applet class, and names the new class Simple. The public keyword makes the class available to other classes that might want to inherit from Simple. In the second part of this book, you inherited from several pre-defined classes. The programmers who wrote those classes made the classes public so the classes would be available to you and other who wanted to extend them. Almost all classes that you write will be public and the Visual J++ wizard always generates public classes.

Keep in mind that this statement is not actually an executable statement but a definition statement. No semicolon appears after the class statement because the statement does nothing more than define a new class, your class, and informs Visual J++ where the existing functionality is to come from. Although the class statement seems a little long at first, you don't even have to write it in most instances. When you use the wizard to generate a skeleton application, the wizard will include an appropriate extended applet from Applet.

When you create your own source code file, as you've done in this chapter, you only need to tell the Create New Class dialog box the name of the existing class that you're extending, your new extended class name, and then click Public to set the public modifier. Visual J++ will generate the correct class definition line for you in the Editing window when you click OK.

You'll add new functionality to your new Simple class in the class body. The body is made up of all statements from the class statement's opening brace to the closing brace at the end of the program.

The init() Method

The next four lines in the Simple applet define a new method called init(). In reality, you are redefining a method. When you subclassed the pre-built Applet class, you gained the capabilities of every method within the Applet class. Once of those methods is called init(). The Applet's init(), however, does not do much. You must redefine the method. Therefore, every time you write an applet, and extend the Applet method, you'll also have to supply an init() method of your own.

Almost every init() that you write will call the resize() method just as your applet does as repeated here:


public void init()
{
resize(320, 240); // applet's window size
}

The resize() method simply informs your class of your applet's window size in the target Web page. You can also insert any other code inside init() that you want executed right after the initial loading of your applet. resize() requires two arguments: an x- and a y-coordinate. Enter the x- and y-coordinate values in pixels. As figure 9.3 illustrates, the x-coordinate determines the width, in pixels, of your applet's window and the y-coordinate determines the height of your applet's window.

 
init() is always the first method executed in your applet.


FIG. 9.3

resize() determines the size of your applet's window.

 
Whenever your applet includes a method that also appears in the class method from which you extended your applet, as does init() in this case, your extended applet's method will always override the original class method. You can be assured that your init() method will execute in place of the original Applet class's init().

The paint() Method

The paint() method should appear in every applet you create and paint() should follow init(). Your applet executes paint() every time your applet window needs redrawing. In a Windows environment, parts of your screen have to be redrawn quite often. For example, you might hide a window and, when you unhide the window, the hidden portion must reappear. Perhaps your end-user minimizes the Web page down to a taskbar icon and then maximizes the window, or resizes the window. As long as you've supplied a paint() method, and you must, you can be assured that your applet window will reappear properly, with the text, colors, and whatever else that appears there.

Here are the Simple applet's paint () lines:


public void paint(Graphics g)
{
// Change subsequent text color to red
g.setColor(Color.red);
// Write a simple message in the window
g.drawString("Very simple!", 75, 100);
}

Unlike init(), paint() requires a parameter inside its parentheses. The parameter is a value that the paint() method operates on. Although Graphics g is a strange parameter, the parameter represents your applet's Web page graphical window. The Graphics g designation is a Java standard designation for your applet window. Even the Visual J++ wizard generates an identical paint() definition line.

Whatever paint() does to the value named g happens to your applet's window. The g is known as a graphics device context. A Windows application does not actually write to your screen; instead, a Windows application writes to windows. The Graphics g parameter tells your applet where to write, namely, the window inside the applet's enclosing Web page.

The next line, shown next, makes a lot of sense despite its wordiness:

g.setColor(Color.red);

Remember that the g represents your Web page applet's window. If you discern that this statement sets your applet window to red you are almost correct. Actually, the statement sets all subsequent output to red. The window remains gray. setColor() will not change an applet's existing colors so you are able to send different colors to the same window by executing multiple setColor() methods between each line of output.

When you see a period following an object (the object, g, represents your applet window), the value to the right of the period will always be a method or a value. Can you tell what setColor() is? setColor() is a method and you know that because of the parentheses that follow its name. The setColor() method is an internal java.awt class method that sets all subsequent output to a specific color. The color must appear inside the parentheses. The color, inside the parentheses, is the setColor() parameter.

Windows is capable of displaying several million colors, although not all graphics cards can display that many colors. As with the Windows API, there exist several ways to represent all the shades of colors that can appear on your screen. Generally, you'll supply an RGB numeric value. RGB stands for Red/Green/Blue. By supplying a number that represents a combination of red, green, and blue color shades, you can specify an exact color value.

Visual J++ makes it easy, however, to specify some standard colors. Therefore, if you don't want to get too picky with finding just that right shade of monkey blue you've always loved on your bedroom ceiling, you can specify one of the colors from Table 9.3 for the argument inside setColor(). Notice that you must precede the color name with the Color object. As mentioned just a couple of paragraphs ago, a period always indicates that a method or a value follows. The Color object is a symbolic object, defined inside the java.awt class package, that represents coloring and you can specify a specific named value by following the Color and period with one of the named color values in table 9.3.

Although the syntax is a little tricky, you can see that the setColor() method is not necessarily hard to understand. For example, you could later print some green text on your applet's window by placing this statement before you print the text:

g.setColor(Color.green);

Table 9.3 Color Values That Represent Specific Colors

black
blue
cyan
darkGray
gray
green
lightGray
magenta
orange
pink
red
white
yellow

OOP-Based Code

The Simple applet's setColor() procedure demonstrates part of the object-based nature of OOP code. For example, in non-OOP languages, the procedures are more important than the data. In OOP languages, the data, or more accurately, the objects, are the primary focus. When you want to set the applet window's printing color, what is the object? The color, the setColor() procedure, or your applet's window? The applet's window is the object. The applet window is the target of the color-setting procedure.
 
The very first item on the Simple applet's setColor() line is g, which represents your applet's graphical drawing window as described earlier in this section. Everything else on the line does something to that object. The object, g, your applet window, gets its color set with the setColor() procedure. Inside setColor, another less-obvious object appears named Color. In other words, you want to set a particular color object to a particular color. The phrase Color.red does just that; Color.red sets the object in question, Color, to red. That object, the red color, is then passed through the setColor() procedure to the graphic applet window, named g in this applet.
 
Don't get bogged down in all this OOP talk! You'll begin thinking in an OOP-aware context in no time at all. At this point, that dissection of the setColor() OOP-relation may distract you more than help you, but at least you are more aware of the OOP under the Java language's layers.

Once the Simple applet sets the color red, the applet sends two words to the applet window with this line:

g.drawString("Very simple!", 75, 100);

drawString() is a commonly-used method that sends strings to the applet's window. drawString() respects the color set by setColor() so the text, Very simple!, will appear in red. Notice the g before the method name. You could, in theory, send different strings to different windows if you knew the multiple window context names by replacing g, your applet's window's context value, with the other windows' context value names.

 
You must enclose the string in quotation marks, or use a String data value (described in the next chapter), for drawString()'s first parameter. If you want quotation marks to appear, you'll have to use ASCII characters to represent the quotation mark symbols and store those ASCII symbols in a data area.

The second and third parameters of drawString() represent the starting x- and y-coordinates of where you want the text to appear. In other words, init() created an applet window that runs 320 pixels across by 240 pixels down. drawString() starts drawing its text, Very Simple!, exactly 75 pixels down and 100 pixels across the applet window.

You now know all you need to know about the Simple applet. You should be proud of yourself! As you can see, Java programming is not difficult to understand, but some of the statements can get tricky. Fortunately, the wizard generates the critical code for you when you use the Visual J++ wizard to generate the program's skeleton. Also, much of the language will become second nature to you once you've written a couple of applets.

Summary

The goal of this chapter was to show you a simple but complete Java program and to walk you through the explanation of every line in the program. You now better understand the "big picture." You know that your applet is actually a subclass, or an inherited version, of an internal applet named Applet that comes with Visual J++. Whereas the Applet is not usable, you can subclass Applet and add your own functionality to make your inherited applet do something unique.

At this point, you have a better understanding of object-oriented programming and of the requirements needed to write a working Java applet. The best thing you can do now, before turning the page to the next chapter, is to change this chapter's Simple applet and make Simple do something else. Start easy; change the applet's output message to your name. Place your name in a different location on the applet window. Change the color. If you really want to make things interesting, print each letter of your name in a different color! (Here's a hint: You'll have to execute the setColor() method once for each letter in your name.)

If you make mistakes, try to fix them. One of the most common mistakes you might make is not getting the case correct on the setColor() and drawString() methods. Be sure that you type these method names exactly as you see them here or Visual J++ will not recognize them and will issue errors. (The error messages are not the most obvious either! It would be nice if Visual J++ would give an error message like, "You misspelled drawString()," but Visual J++ offers a more technical explanation when you misspell a method, such as Cannot find method drawstring.

In the next chapter, you will begin to learn the deep details of the Java language. It's time to get down to the nitty-gritty details of data types and programming control statements and chapter 10 takes you there in a hurry.

Here are the points this chapter covered:


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.